Gets the contents of an IFrame outside the iframe

Methods a

Through the contentWindow and contentDocument apis:

var iframe = document.getElementById("iframe1");
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
var idocument = iframe.contentDocument;
console.log("window",iwindow);// Get the window object of iframe
console.log("document",idoc);  // Get the document of iframe
console.log("html",idoc.documentElement);// Get the HTML of iframe
Copy the code

Ifame. ContentWindow gets the window object of the ifame, and ifame. ContentDocument gets the Document object of the ifame.

Way 2

In combination with the Name attribute, get the frames provided by the window:

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

Gets content inside an iframe that is outside the iframe

window.parent Gets the parentwindowObject, if still iframe, to that iframewindowobjectwindow.top Gets the top-level containerwindowObject, that is, the document that you open the page toCopy the code

Call the methods and variables defined in the parent page in iframe

window.parent.window.parentMethod();
window.parent.window.parentValue;
Copy the code

Methods and variables that operate on iframe child pages on the parent page

window.frames["iframe_Name"].window.childMethod();
window.frames["iframe_Name"].window.childValue;
Copy the code

conclusion

Note the following points when using Iframe:

  1. Make sure to wait until the iframe is loaded. If you call a method or variable before the iframe is loaded, an error will occur.
  2. If the iframe is linked to an external page, the security mechanism cannot use the same communication method under the domain name.

Check if the iframe is loaded successfully

iframe.onload = function() {
    // TODO
}
Copy the code

Different domain communication

The parent page passes data to the child page

The hash value of the Location object is used to pass communication data. Add a data string to the SRC of the iframe in the parent page, and then somehow get the data in the child page immediately.

The child page passes data to the parent page

Using a proxy IFrame, it is embedded in the child page, and the parent page must remain co-domain, and then through it to make full use of the implementation principle of the above co-domain communication mode, the data of the child page is passed to the proxy IFrame, and then because the proxy IFrame and the main page are co-domain, So the main page can get this data in a symbiotic way.