Getting the Body Content of an iFrame in Pure JavaScript
JavaScript enables the manipulation of elements within the current HTML document. However, retrieving the content of an iframe requires a different approach. This article provides a comprehensive solution in pure JavaScript, following the methods used by the jQuery framework.
Obtaining the iFrame Element
To start, identify the target iframe using its ID or CSS selector:
var iframe = document.getElementById('id_description_iframe');
Accessing the iFrame Content
Now, to access the content of the iframe, you can utilize a solution employed by jQuery:
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
In Internet Explorer, the contentWindow property is used, while other browsers prefer contentDocument. This OR condition ensures compatibility.
Selecting Elements Within the iFrame
With access to the iframe document, you can select specific elements using the usual methods:
var iframeContent = iframeDocument.getElementById('frameBody');
Invoking Functions and Accessing Variables
To interact with functions and variables defined within the iframe's JavaScript context, access its window element:
var iframeWindow = iframe.contentWindow; // Call global functions var myVar = iframeWindow.myFunction(param1 /*, ... */);
Considerations
Note that all these operations require adhering to the same-origin policy. If cross-origin access is needed, specific measures are required, such as modifying the Content-Security-Policy header.
The above is the detailed content of How to Get the Content of an iFrame Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!