Access the DOM inside an iframe with Javascript
Luke Harby asked me in Mastodon:
I am trying to write a bookmarklet but once I have it working I need to target an iframe, not sure if that is going to be possible, but I will endeavour to find out.
He said the magic words in the second paragraph: same domain.
If you have a web page that includes an iframe from the same domain (or more specifically, they are of Same Origin), you can access the DOM through with HTMLIFrameElement.contentDocument:
<iframe id="target" src="<https://example.com/iframe>">
<!-- imagine this is what the iframe'd content is -->
<ul class="blog-posts">
<li><a href="/blog-post-1">First post</a></li>
<li><a href="/blog-post-2">Second post</a></li>
<li><a href="/blog-post-3">Third post</a></li>
</ul>
</iframe>
Once the iframe has loaded (in this use case, Luke was building manually triggered bookmarklet so no need for programmatic wait), you can access it with
const iframe = document.querySelector('#target');
const iframeDOM = iframe.contentDocument;
const blogPosts = iframeDOM.querySelectorAll('ul.blog-posts a')
console.log(blogPosts.map(post => post.textContent))
If the iframe is in a different domain,
contentDocument
returns
null
.
If something above resonated with you, let's start a discussion about it! Email me at juhamattisantala at gmail dot com and share your thoughts. In 2025, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.