Home > Article > Web Front-end > Detailed explanation of javascript parent-child page communication examples_javascript skills
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;
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节点 }
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); };
www.static.abc.com subpage:
I hope this article will be helpful to everyone’s JavaScript programming design.