JavaScript iframe Data sharing interface implementation method

  • 2020-11-25 07:07:36
  • OfStack

Passing data from iframe to parent or child Windows is a hassle, and it would be nice if we could write a one-and-done interface. Here's how to do it. The principle is to cache the data to the window window.top, so that no matter how the hierarchy of the parent window of the child window changes, the data will always remain unchanged.

The code is as follows:


var share={ 
data:function(name,value){ 
var top=window.top, 
cache=top['_CACHE']||{}; 
top['_CACHE']=cache; 
return value?cache[name]=value:cache[name]; 
}, 
removeData:function(name){ 
var cache=window.top['_CACHE']; 
if(cache&&cache[name]) 
{ 
delete cache[name]; 
} 
} 
}; 
share.data('mayi','https://www.ofstack.com'); 

The above code to achieve our requirements, the code is relatively simple, you can analyze 1 by yourself, if there are any questions you can comment.

Do you know how Iframe passes values between JS? Let me give you a brief introduction.

1. Get the elements of the parent page in the iframe child page:

a > window. parent. document this is the object to get the parent page document;
b > If you want to get the method in the parent page js: window.parent.xxxx (); xxxx() was the method;

2. Get the elements in the iframe child page from the parent page:
a >
var child = document.getElementByIdx_x("mainFrame").contentWindow; //mainFrame This id is the id of the parent page iframe
child.document; // Get the document object in the subpage;


Related articles: