Getting contents of iframe with javascript

javascript

To get the contents of an iframe using JavaScript, you can use the contentDocument property of the iframe element.

Here’s an example code snippet that demonstrates how to get the contents of an iframe:

const iframe = document.querySelector('#my-iframe'); // Get the iframe element
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Get the document object inside the iframe

// Access and manipulate the contents of the iframe document
const iframeBody = iframeDoc.querySelector('body');
iframeBody.innerHTML = 'Hello, world!'; // Change the contents of the iframe

In this example, we first get a reference to the iframe element using the querySelector() method. We then access the document object inside the iframe using the contentDocument property or the contentWindow.document property.

Once we have a reference to the iframe document object, we can manipulate its contents using regular DOM methods. In this example, we get a reference to the body element of the iframe document and change its innerHTML to display the message “Hello, world!“.

Note that accessing the contents of an iframe from a different domain may be restricted due to the Same Origin Policy. If the iframe is hosted on a different domain than the parent document, you may need to use a server-side solution or a postMessage API to communicate between the two documents.