Javascript iframe Interactive and Compatible with Various Browser Solutions

  • 2021-07-02 23:19:47
  • OfStack

In Web front-end development, we often use iframe control.

However, when this control is internal and diplomatic, the keywords used by each browser are often different, which is very troublesome. In order to get the window object in the sub-iframe, each browser has its own designation, some are window, some are contentWindow and so on, which we may not know.

But visit the parent page from the child page, and everyone in this page is window. parent.

Then through this feature, we can pass our own window object to the parent page in the child page, so that the parent page can easily access the child page, and no longer have to worry about how to get window object from iframe object.

Without saying anything, let's look at the code first:

Parent page code:


window.iframeWindow = null;
function frameReady(subWindow){
window.iframeWindow = subWindow; // Assignment 
}; 
<iframe src = "xx" ></iframe> 

Sub-page code:


$(function(){
window.parent.frameReady(window);
}); 

Through the above simple code, you can access the iframeWindow object in the parent page, and directly get the window object of the child page, which is very mindless and very easy to use.

What if I have multiple iframe?

This situation will be a little more complicated, but it doesn't matter. If we want to continue to use the above scheme, we will analyze the current situation in 1:

1. We should need a collection object similar to iframeWindows to manage window objects for all child pages.

2. When each child page calls parent. frameReady, it must rely on the parent page to have a unique name, so that we can accurately access each iframe in the parent page

Then this is simple, sub-page to do, nothing more than a name, number, let's look at the code


window.subWindowName = "HelloWorldWindow";
$(function(){
window.parent.frameReady(window.subWindowName, window);
}); 

Then all the parent page has to do is reconstruct frameReady and add 1 parameter


window.iframeWindows = {}; // This place has become 1 Objects 
function frameReady(name, window){
window.iframeWindows[name] = window;
};
function getSubWindow(name){
return window.iframeWindows[name];
}

Summary:

Pages built with this scenario have the following advantages:

1. The interaction between parent and child pages only depends on the parent keyword (in the previous way, it depends not only on parent, but also on other uncertain keywords such as contentWindow and window, and most importantly, the support of parent is very good)

2. window objects are unified, which reduces the reference chain requested again every time it is used and improves the running speed

3. The most important point: The code is much easier to write.


Related articles: