What is the correct way to get innerhtml of iframe?

by elisha_langworth , in category: Javascript , 3 months ago

What is the correct way to get innerhtml of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jasen , 3 months ago

@elisha_langworth 

To get the innerHTML of an iframe, you can use the contentDocument property if you are working with an iframe that loads content from the same domain. Here is an example:


First, you need to select the iframe element using JavaScript:

1
var iframe = document.getElementById('my-iframe');


Then, you can access the innerHTML of the iframe's content using the contentDocument property:

1
2
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var iframeHTML = iframeDocument.documentElement.innerHTML;


Make sure to replace 'my-iframe' with the actual id of your iframe element.


However, if you are trying to access content from a different domain, due to security restrictions you won't be able to access the iframe's innerHTML directly.

Member

by brandy , 3 months ago

@elisha_langworth 

Instead, you can use the postMessage API to communicate between the parent window and the iframe, and then retrieve the innerHTML from the iframe's content window. Here is an example:


In the parent window: 1


var iframe = document.getElementById('my-iframe'); var iframeWindow = iframe.contentWindow;


// Send a message to the iframe requesting its innerHTML iframeWindow.postMessage('getInnerHTML', '*');


// Listen for the response message from the iframe window.addEventListener('message', function(event){ if(event.origin === 'https://example.com' && event.data === 'innerHTMLResponse'){ var iframeHTML = event.data.innerHTML; // Use the iframeHTML value } });


In the iframe: 1


// Listen for the postMessage request from the parent window window.addEventListener('message', function(event){ if(event.source === window.parent && event.data === 'getInnerHTML'){ var iframeHTML = document.documentElement.innerHTML; // Send the innerHTML back to the parent window window.parent.postMessage({ origin: 'https://example.com', data: 'innerHTMLResponse', innerHTML: iframeHTML }, '*'); } });


In this example, the parent window requests the innerHTML of the iframe by sending a postMessage to the iframe's content window. The iframe then listens for this request, retrieves its innerHTML, and sends it back to the parent window using another postMessage. The parent window listens for the response message and retrieves the innerHTML from the event data. Remember to replace 'https://example.com' with the actual domain of the parent window.