How to reach inside of an iframe with Javascript

I know this stuff is pretty basic, but as always, this post is more self serving than anything else. It’s a bookmark and a resource for my own benefit as well. So here it goes…

Let’s say you have a wufoo form or iframe embedded on your page and you wish to add some events to it or control interactions with javascript. It’s pretty easy to reach inside and gain access to the elements within. Simply do the following:

                _iframe = document.getElementById('iframeId');
                _doc = _iframe.contentDocument || _iframe.contentWindow.document;

The code above accesses the iframe element in your page. Then you simply drill down and select the first available “document” inside the iframes context.

Pretty simple, but very useful. Keep in mind, you’ll need to access the iframe from the same protocol so if the iframe is loading from “https” then your script must also be calling from “https”.


Leave a Reply

Your email address will not be published. Required fields are marked *