How to get document object of iframe?

Member

by ryleigh , in category: Javascript , 7 months ago

How to get document object of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 7 months ago

@ryleigh 

In order to get the document object of an iframe, you can use the contentWindow or contentDocument property of the iframe element. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
    <title>Get document object of iframe</title>
</head>
<body>

<iframe id="myIframe" src="https://www.example.com"></iframe>

<script>
    var iframe = document.getElementById('myIframe');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Now you can access the document object of the iframe
    console.log(iframeDoc);
</script>

</body>
</html>


In the script section, we first select the iframe element using document.getElementById('myIframe'). Then we check if the iframe has a contentDocument property, if not we fallback to using contentWindow.document. This will give you access to the document object of the iframe, which you can then use to manipulate its contents.

Related Threads:

How to get height of pdf document load in iframe?
How to view an object embedded with a document in mongodb?
How to access the <img /> in document from iframe?
How to get all nested iframes on document?
How to get the duration of a video in iframe?
How to add an inline svg behind an iframe object?