Summary of javascript parent and child page interaction tips

  • 2020-03-30 03:41:39
  • OfStack

Frames are used to hold child pages, which can be either iframe or frameset. The window object is a global object, and all functions and objects on the page are in its scope.
1. Parent represents the parent window. If there are several layers nested in the parent window, top represents the top-level parent window.
Self represents the window itself.


if(self==top){//} determines whether the window is at the top level
if(self==parent){}// Can also be 

2.1. The parent page accesses the child page elements. The idea is that the elements of the child page are in its window.document object, get it first and then we'll be done.
It is best to set the name property of the frame, which is the most convenient operation. Such as


<iframe name="test" src="child.html"></iframe>

If you want to get the element with id 'menu' in child.html, you can write:


window.frames["test"].document.getElementById('menu'); 
//Since all functions are stored in the window object, remove the window at the beginning:
frames["test"].document.getElementById('menu'); 
//In the browser, the name property of the frame is by default equivalent to the window object of the child page, so it can be further abbreviated:
test.document.getElementById('menu');

2.2 the parent page accesses the child page function or object. The function and object of the child page are in its window object.


//If child.html defines the showMesg function and needs to be called from the parent, write it like this
window.frames['test'].showMesg(); 
//shorthand
test.showMesg(); 
//The same is true for objects
alert(test.person);

3.1 the child page accesses the parent page element. In the same way as 2.1, get the parent window.document object first


parent.window.document.getElementById('parentMenu'); 
// shorthand  
parent.document.getElementById('parentMenu');

3.2, the child page accesses the parent page function or object. In the same way as 2.2, get the window object of the parent window first.


parent.parentFunction();

Finally, I will mention the same origin policy of js, that is, js code located in A website does not allow access to content located in B website, even if the code comes from B website. If the frame is a page from another web site, the browser should prompt the 'no permissions' error when visiting each other in this way.


Related articles: