Home  >  Article  >  Web Front-end  >  Analyze how to operate iframe parent-child (internal and external) pages using JS?

Analyze how to operate iframe parent-child (internal and external) pages using JS?

零下一度
零下一度Original
2017-06-17 10:38:002092browse

This article mainly introduces how to use JS to operate the parent-child (internal and external) pages of an iframe. It includes how to operate the iframe, control the js code outside the iframe in the iframe, and control the child in the parent frame. iframe operations, etc. Friends in need can refer to it.

This article mainly introduces to you how to use JS to operate the iframe parent-child (internal and external) pages, and shares it for your reference and study. Let’s take a look at the detailed introduction:

1. Get the content in the iframe

Before we start, let’s first take a look at how to get the content in the iframe. The two main APIs for getting the content in the iframe are contentWindow, and contentDocument iframe.contentWindow, get the iframe's window object iframe.contentDocument, get the iframe's document object these two APIs It’s just the method provided by DOM nodes (i.e. getELement series objects)


 var iframe = document.getElementById("iframe1");
 var iwindow = iframe.contentWindow;
 var idoc = iwindow.document;
  console.log("window",iwindow);//获取iframe的window对象
  console.log("document",idoc); //获取iframe的document
  console.log("html",idoc.documentElement);//获取iframe的html
  console.log("head",idoc.head); //获取head
  console.log("body",idoc.body); //获取body

The actual situation is as follows:

It’s also simpler The method is to combine the Name attribute and obtain it through the frames provided by the window.


<iframe src ="/index.html" id="ifr1" name="ifr1" scrolling="yes">
 <p>Your browser does not support iframes.</p>
</iframe>
<script type="text/javascript">
 console.log(window.frames[&#39;ifr1&#39;].window);
console.dir(document.getElementById("ifr1").contentWindow);
</script>

In fact, window.frames['ifr1'] returns the window Object, that is,


window.frames[&#39;ifr1&#39;]===window

It depends on which method you want to use to obtain the window object. Both are fine, but I prefer the second one to use frames[xxx ]. Because there are few letters~ Then, you can control the DOM content in the iframe.

2. Get the parent content in the iframe

Similarly, in the same domain, the parent page can get the content of the child iframe. Then the child iframe can also operate on the content of the parent page. In an iframe, it can be obtained through several APIs mounted on the window.

  • window.parent Get the upper-level window object, if it is still an iframe It is the window object of the iframe

  • window.top Get the window object of the top-level container, that is, the document you open the page

  • window.self Returns a reference to its own window. It’s understandablewindow===window.self(brainless)

As shown in the picture:

After obtaining it, we can perform related operations. In an iframe in the same domain, we can cleverly use the black technology of iframe to implement some tricks.

iframe polling

It is said that a long time ago, we The asynchronous sending of requests is implemented using iframe~! How is it possible!!! As evidenced by real historical data (google it yourself), at that time, in order not to jump to the page, the iframe was used when submitting the form. Nowadays, front-end development is really fast, websocket, SSE, ajax, etc. The emergence of incredible skills has subverted iframe. Now it can basically only live in IE8 and 9 browsers. However, the baby thinks that this eliminates the need to understand iframe, but the reality is so cruel, we still need to be compatible with IE8+. Therefore, we still need to dabble in the tricks of iframe to implement long polling and long connections.

iframe long polling

If you have written ajax children's shoes, you should know that long polling is to execute the original function again when ajax's readyState = 4. Can. The same is true for using iframe here. Create the iframe asynchronously, then reload, negotiate with the backend, watch the backend brothers put the returned information, and then get the information inside. Here it is placed directly in the body.


var iframeCon = docuemnt.querySelector(&#39;#container&#39;),
 text; //传递的信息
 var iframe = document.createElement(&#39;iframe&#39;),
 iframe.id = "frame",
 iframe.style = "display:none;",
 iframe.name="polling",
 iframe.src="target.html";
 iframeCon.appendChild(iframe);
 iframe.onload= function(){
 var iloc = iframe.contentWindow.location,
 idoc = iframe.contentDocument;
 setTimeout(function(){
 text = idoc.getElementsByTagName(&#39;body&#39;)[0].textContent;
 console.log(text);
 iloca.reload(); //刷新页面,再次获取信息,并且会触发onload函数
 },2000);
 }

This way you can achieve the effect of ajax long polling. Of course, here we just use reload to obtain. You can also add iframe and delete iframe to send information. These are all applied according to specific scenarios. In addition, asynchronous loading of js files can also be implemented in iframes. However, iframes and homepages share a connection pool, so it is still very painful. Now they are basically banned by XHR and hard callback, so I won’t introduce them too much here.

1.js operates the parent page element code on the iframe subpage:


window.parent.document.getElementByIdx_x("父页面元素id");

2.js obtains the iframe subpage element code on the parent page as follows:


window.frames["iframe_ID"].document.getElementByIdx_x("子页面元素id");

3. The code for jquery to obtain the parent page element in the iframe child page is as follows:


##

$("#objid",parent.document)

4. jquery in the parent page The page gets the elements of the iframe subpage


$("#objid",document.frames(&#39;iframename&#39;).document)

5. Call the methods and variables defined in the parent page in the iframe:


window.parent.window.parentMethod();
window.parent.window.parentValue;

6. Methods and variables for operating iframe child pages on the parent page


window.frames["iframe_ID"].window.childMethod();
window.frames["iframe_ID"].window.childValue;

1. Communication between parent and child pages in the same domain

Parent page parent.html


<html>
<head>
 <script type="text/javascript">
  function say(){
   alert("parent.html");
  }
  function callChild(){
   myFrame.window.say();
   myFrame.window.document.getElementById("button").value="调用结束";
  }
 </script>
</head>
<body>
 <input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()"/>
 <iframe name="myFrame" src="http://caibaojian.com/child.html"></iframe>
</body>
</html>

Child page child.html


<html>
<head>
 <script type="text/javascript">
  function say(){
   alert("child.html");
  }
  function callParent(){
   parent.say();
   parent.window.document.getElementById("button").value="调用结束";
  }
 </script>
</head>
<body>
 <input id="button" type="button" value="调用parent.html中的say()函数" onclick="callParent()"/>
</body>
</html>

Precautions

Make sure to operate after the iframe is loaded. If you start calling methods or variables before the iframe is loaded, an error will occur. There are two ways to determine whether the iframe has been loaded:

1. Use the onload event on the iframe

2. Use document.readyState=="complete" to determine

2. Cross-domain parent-child page communication method

If the iframe is linked to an external page, the communication method under the same domain name cannot be used because of the security mechanism.

1. The parent page transfers data to the child page

The trick is to use the hash value of the location object and pass the communication data through it. Just add an extra datastring after setting the src of the iframe on the parent page, and then use some method to instantly obtain the data here in the child page, for example:

1.1 Set the timer through the setInterval method in the sub-page, and monitor the changes in location.href to obtain the above data information

1.2. Then the sub-page uses this data The information is processed accordingly

2. The child page transfers data to the parent page

The implementation technique is to use a proxy iframe, which is embedded in the child page and must remain the same as the parent page. domain, and then make full use of the implementation principle of the first communication method above to pass the data of the subpage to the proxy iframe. Then, since the proxy iframe and the main page are in the same domain, the main page can use the same domain method. Get these data. Use window.top or window.parent.parent to obtain a reference to the top-level window object of the browser.

The above is the detailed content of Analyze how to operate iframe parent-child (internal and external) pages using JS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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