Using JS to operate on iframe Parent and Child (internal and external) pages

Source: Internet
Author: User

Using JS to operate on iframe Parent and Child (internal and external) pages

This article mainly introduces how to use JS to operate on iframe Parent and Child (internal and external) pages, and shares it for your reference. Let's take a look at the details below:

1. Get the content in iframe

Before getting started, let's first look at how to get the content in iframe. The main two APIs for getting the content in iframe are:contentWindow, AndcontentDocument iframe.contentWindowTo obtain the window object of iframe.iframe.contentDocumentTo get the document Object of iframe. These two APIs are only provided by DOM nodes (I .e., getELement series objects)

Var iframe = document. getElementById ("iframe1"); var iwindow = iframe. contentWindow; var idoc = iwindow.doc ument; console. log ("window", iwindow); // obtain the window object console of iframe. log ("document", idoc); // obtain the document console of iframe. log ("html", idoc.doc umentElement); // obtain the html console of iframe. log ("head", idoc. head); // get head console. log ("body", idoc. body); // get the body

The actual situation is as follows:

In addition, the simpler method is to use the frames provided by window to obtain the object by combining the Name attribute.

<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['ifr1'].window);console.dir(document.getElementById("ifr1").contentWindow);</script>

Actuallywindow.frames[‘ifr1']The returned window object is

window.frames['ifr1']===window

Here, we can see which method you want to use to obtain the window object. Both are acceptable, but I prefer the second method to use frames [xxx]. Because there are few letters ~ Then you can control the DOM content in iframe.

2. Get the parent content in iframe

Similarly, in the same domain, the parent page can obtain the content of the sub-iframe, so the sub-iframe can also operate on the content of the parent page. In iframe, you can obtain it through several APIs mounted on the window.

  • window.parentObtains the window object of the previous level. If it is still iframe, It is the window object of the iframe.
  • window.topObtain the window object of the top-level container, that is, the document that you open the page.
  • window.selfReturns the reference of the current window. Understandablewindow===window.self(Brainchild)

:

After obtaining the information, we can perform related operations. In the iframe of the same domain, we can use the black Technology of iframe to implement some trick.

Iframe round robin

A long time ago, we used iframe to send requests asynchronously ~! How is it possible !!! Real historical data is evidence (self-google). At that time, iframe was used to submit the form to avoid page Jump. Now, Nima's front-end development is so fast that the emergence of websocket, SSE, ajax, and anti-day skill has overturned iframe, and now it is basically only available in IE8 and 9 browsers. However, the baby thinks that we don't need to know iframe, but the reality is so cruel that we still need to be compatible with IE8 +. Therefore, we still need to explore how to implement long polling and long connection trick in iframe.

Iframe long polling

If you have written ajax, you should know that long polling is to execute the original function again when ajax readyState is 4. The same is true if iframe is used here. Create an iframe asynchronously, reload it, and negotiate with the background. Check that the back-end friends put the returned information and then obtain the information. Here, they are directly placed in the body.

Var iframeCon = docuemnt. querySelector ('# iner'), text; // The information passed var iframe = document. createElement ('iframe'), 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 ('body') [0]. textContent; console. log (text); iloca. reload (); // refresh the page, obtain information again, and trigger the onload function}, 2000 );}

In this way, you can achieve the effect of ajax long polling. Of course, here we only use reload for retrieval. You can also add iframe and delete iframe to send information, which are applicable to specific scenarios. In addition, js files can be asynchronously loaded in iframe. However, iframe and the Home Page share the connection pool, so it is still very painful. Now they are basically banned by XHR and hard calllback, I will not introduce it more here.

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

Optional bytes parent.doc ument. getElementByIdx_x ("parent page element id ");

2. The code for js to obtain the iframe sub-page element on the parent page is as follows:

Window. frames ["iframe_ID" 2.16.doc ument. getElementByIdx_x ("subpage element id ");

3. The code for jquery to obtain the element of the parent page on the iframe subpage is as follows:

$("#objid",parent.document)

4. jquery obtains the element of the iframe subpage on the parent page.

$("#objid",document.frames('iframename').document)

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

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

6. Operate the iframe sub-page methods and variables 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> 

Child page child.html

<Html> 

Notes

Make sure that the operation is performed after the iframe is loaded. If the iframe is not loaded, an error occurs when calling the methods or variables. There are two ways to determine whether iframe is loaded successfully:

1. Use the onload event on iframe

2. Usedocument.readyState=="complete"To judge

Ii. Cross-origin parent-child page communication method

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

1. The parent page transmits data to the Child page

The trick is to use the hash value of the location object to transmit communication data. Add a data string after the src of iframe on the parent page, and then obtain the data in the subpage in some way. For example:

1.1 set the timer and listen to the timer through the setInterval method on the subpagelocation.hrefTo obtain the above data information.

1.2. Then, the Child page performs logical processing based on the data information.

2. The child page transmits data to the parent page

The implementation technique is to use a proxy iframe, which is embedded into the Child page and must be in the same domain as the parent page, then, the sub-page data is transmitted to the proxy iframe Based on the implementation principle of the first communication mode. Then, because the proxy iframe and the home page are in the same domain, therefore, you can use the same domain to obtain the data on the home page. Usewindow.topOrwindow.parent.parentObtains the reference of the top-level window object in the browser.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.