Get Access to IFrame Elements with JavaScript

If your job requires lots of data entry, bookmarklets can be your best friend. Simply code up a bit of JavaScript magic, paste it into your browser as a new favorite, and voilà, your job is done. But what happens when the form you’re filling out is inside an iframe? The usual tricks don’t work.

Luckily, I discovered a workaround: Using either contentDocument or contentWindow.document (whichever one your browser supports), you can target the iframe’s elements just like you would any element in the main page.

Here’s a function that populates the name and email fields in the example form below:

function update_fields() {
	var iframe = document.getElementById('exampleForm');
	var iframedoc = iframe.contentDocument? iframe.contentDocument: iframe.contentWindow.document;

	var id = 'name';
	var val = 'John Smith';
	if (iframedoc.getElementById(id)) { iframedoc.getElementById(id).value = val; }

	var id = 'email';
	var val = '';
	if (iframedoc.getElementById(id)) { iframedoc.getElementById(id).value = val; }

Click the Example button to execute the function, populate the fields:

Now, to create the bookmarklet, strip out all of the tabs and line breaks, then copy and paste into a new bookmark in your browser:

It’ll look something like this:

creating the bookmarklet in Chrome

To test it out, scroll up, click the Clear button, then your new bookmarklet. That’s it. Easy, right? Hopefully this will save you from some tedium.



This post was published on February 13th, 2018 by Robert James Reese in JavaScript Before using any of the code or other content in this post, you must read and agree to our terms of use.