JS operation on the inside and outside of the IFRAME (parent-child) page

Source: Internet
Author: User

How to operate the iframe , 1. Control the JS code outside the iframe inside the iframe . 2. Act on the parent frame to the child iframe.

Get the content in the IFRAME

The main two APIs are Contentwindow, and Contentdocument Iframe.contentwindow, which gets the window object iframe.contentdocument of the IFRAME, The two APIs that get the document object for an IFRAME are just the way the DOM node provides (that is, the GetElement series object)

 variframe =Document. getElementById ("Iframe1");varIwindow = Iframe.contentwindow;varIDoc = iwindow.document;Console. log ("Window", Iwindow);//Gets the window object for the IFRAME        Console. log ("Document", IDoc);//Get the document for the IFRAME        Console. log ("HTML", idoc.documentelement);//Get the HTML for the IFRAME        Console. log ("Head", Idoc.head);//Get head        Console. log ("Body", idoc.body);//Get body

The actual situation is as follows:

Another simpler way is to combine the Name property with the frames provided by 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[' IFR1 '].window); console. Dir (document. getElementById ("IFR1"). Contentwindow); </Script> 

In fact window.frames[' IFR1 ' return is the Window object, that is,

window.frames[‘ifr1‘]===window

Here's how you want to get the Window object, both of which are OK, but I prefer the second one to use frames[xxx]. Because the letters are small, and then you can manipulate the DOM content inside the IFRAME.

Getting parent content in an IFRAME

Similarly, under the same domain, the parent page can get the contents of the child iframe, and the child IFrame can also manipulate the contents of the parent page. In an IFRAME, it can be obtained by using several APIs that are mounted on the window.

window.parent 获取上一级的window对象,如果还是iframe则是该iframe的window对象window.top 获取最顶级容器的window对象,即,就是你打开页面的文档window.self 返回自身windowwindow===window.self(脑残)

: a chestnut ~ OK, after we get it, we can do the relevant operation. In the same domain iframe, we can skillfully use the black technology of the IFRAME to achieve some trick.

The polling of the IFRAME

In the words of a long long time ago, we implement asynchronous send request is implemented using IFRAME ~ ~ How can it be!!! True historical data for the card (self-Google), then in order not to jump page, submit the form is submitted using the IFRAME. Now, the front-end development is really fast, Websocket,sse,Ajax , such as the emergence of skill, subversion of the IFRAME, now basically only live in ie8,9 browser. However, the baby thought that this can not understand the IFRAME, and the reality is so cruel, we currently need to be compatible with ie8+. Therefore, the IFRAME realizes long polling and long connection trick we still need to dabble.

IFRAME Long Polling

If you write Ajax child shoes, you should know that long polling is in the Ajax readystate = 4, the original function can be executed again. This is also the same as using an IFRAME, asynchronously create an IFRAME, and then reload, and the background to negotiate good, look at the background elder brothers will return the information in, and then get inside information can. Here it is placed directly in the body.

varIframecon = Docuemnt.queryselector (' #container '), text;//delivery of informationvariframe =Document. createelement (' iframe '), iframe.id ="Frame", Iframe.style ="Display:none;", iframe.name="Polling", iframe.src="Target.html"; Iframecon.appendchild (iframe); iframe.onload= function(){varIloc = Iframe.contentwindow.location,idoc = Iframe.contentdocument;settimeout ( function(){text = Idoc.getelementsbytagname (' body ')[0].textcontent;Console. log (text); Iloca.reload ();//Refresh the page, retrieve the information again, and trigger the OnLoad function}, -);}

This makes it possible to achieve the long polling effect of Ajax. Of course, this is only done using reload, and you can also add an IFRAME and delete the IFRAME to send messages, which are all based on specific scenarios. In addition, in the IFRAME can also implement asynchronous loading JS file, however, the IFRAME and the home page is a shared connection pool, so it is very painful, and now basically have been xhr and hard calllback banned, here also more introduction.

1.js manipulating the parent page element code on the IFRAME sub-page:

window.parent.document.getElementByIdx_x ("Parent page element ID");

2.js gets the IFRAME child page element code on the parent page as follows:

window.frames["iframe_id"].document.getelementbyidx_x ("Child page Element ID");

3. jquery Gets the parent page element code in the IFRAME sub-page as follows:

$ ("#objid", parent.document)

4. jquery Gets the elements of the IFRAME child page on the parent page

$ ("#objid", Document.frames (' Iframename '). 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 manipulating the IFRAME child page on the parent page

window.frames["iframe_id"].window.childmethod (); window.frames["iframe_id"].window.childvalue;

I. Communication of parent-child pages under the same domain

Parent page parent.html

Sub-page child.html

Precautions

To ensure that the IFRAME is loaded and then done, an error occurs if the IFRAME has not yet been loaded to begin invoking the inside method or variable. There are two ways to determine whether an IFRAME is loaded or not:

1. OnLoad event on IFrame

2. Use document.readystate== "complete" to judge

Two, cross-Domain parent-Child page communication method

If the IFRAME is linked to an external page, the security mechanism cannot use the same domain as the communication mode.

1. Parent page passing data to child pages

The technique of implementation is to use the hash value of the location object to pass the communication data through it. Add a data string to the parent page to set the IFRAME after SRC, and then in a sub-page, in some way can get the data here in real time, for example:

1.1 In the sub-page through the SetInterval method to set the timer, listen to location.href changes to obtain the above data information

1.2. The sub-pages are then logically processed according to the data information

2. Child pages passing data to the parent page

The trick is to use a proxy iframe, which is embedded in the sub-page, and the parent page must remain the same domain, and then through it to take full advantage of the first communication method above the implementation principle of the page to pass the data to the proxy iframe, and then because the agent's IFrame and the main page is the same domain, So the main page can take advantage of the same domain to get this data. Use Window.top or window.parent.parent to get a reference to the topmost window object of the browser.

Previously wrote an IFRAME adaptive height of the article, is through the IFRAME sub-page operation to achieve. You can also see.

Reference: http://www.cnblogs.com/sydeveloper/p/3712863.html

JS operation on the inside and outside of the IFRAME (parent-child) page

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.