Home > Web Front-end > JS Tutorial > body text

Detailed explanation of javascript parent-child page communication examples_javascript skills

WBOY
Release: 2016-05-16 15:49:55
Original
1460 people have browsed it

The example in this article describes the implementation method of JavaScript parent-child page communication. Share it with everyone for your reference. The specific analysis is as follows:

If a page with the domain www.abc.com contains an iframe with a name attribute value of childFrame, and the domain of this iframe is static.abc.com. Then you can set the domain of the parent page to abc.com, and the domain of the child page to abc.com, and then achieve parent-child page communication (I am a bit confused here about the concepts of parent-child pages and cross-domain.

You can also achieve mutual access between parent and child pages without using the above method.
The method is: use window.frames[0] or window.frames["childFrame"] on the parent page. What is returned is a Window object, and then you can pass:

var childWindow = window.frames[0];
// 或者 window.frames["childFrame"] 或者直接childFrame 或者childFrame.window 
var childDoc = childWindow.contentDocument || childWindow.document; 

Copy after login

Use childWindow to access the function that executes the definition of the subpage, and use childDoc to access the DOM node of the subpage.

To access the parent page, the child page can pass parent (Window object). If a page is already a top-level page, parent==self will return true:

if(parent != self) {
// 当前页面有父页面 
  // 调用父页面的函数 
  parent.parentFunc(); 
  var parentDoc = parent.contentDocument || parent.document; 
  // 访问父页面的DOM节点 
}
Copy after login

www.abc.com parent page:

document.domain = 'abc.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://static.abc.com/';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
  var doc = ifr.contentDocument || ifr.contentWindow.document;
  // 在这里操纵子页面
  alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
};

Copy after login

www.static.abc.com subpage:

Copy code The code is as follows:
document.domain = 'abc.com';

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!