IFRAME contentWindow is null
I like clean code so I do what I can to avoid unwanted JavaScript global variables. I initially thought that keys(window)
would give me window
property leaks but that didn't work because browsers returned different results, so I moved on to using an IFRAME
to compare default window property keys.
When I first tried this method, I got a lame error about an IFRAME
element's contentWindow
property being null
. Ugh. It didn't take long to figure out why: you need to wait until the IFRAME
has loaded to get the contentWindow
:
var iframe = document.createElement('iframe');
iframe.onload = function() {
// contentWindow is set!
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);
Of course you'll want to add the onload
event before setting the src
. If you use the load
event to check for the contentWindow
property, you'll be in business!
![Convert XML to JSON with JavaScript]()
If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium. The experience has been great: using JavaScript to create easy to write, easy to test, native mobile apps has been fun. My...
![5 Awesome New Mozilla Technologies You’ve Never Heard Of]()
My trip to Mozilla Summit 2013 was incredible. I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out. MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...
![Firefox Marketplace Animated Buttons]()
The Firefox Marketplace is an incredibly attractive, easy to use hub that promises to make finding and promoting awesome HTML5-powered web applications easy and convenient. While I don't work directly on the Marketplace, I am privy to the codebase (and so...
![MooTools 1.2 OpenLinks Plugin]()
I often incorporate tools into my customers' websites that allow them to have some control over the content on their website. When doing so, I offer some tips to my clients to help them keep their website in good shape. One of the tips...
Don’t you need to append your iframe element to a DOM tree so that the browser fetches its target content ? I mean, I know that old IE will load scripts as you parse an “HTML string” but in modern browsers, I thought that the asset does not get loaded until you append the element to a document (and in my opinion this it what makes constructors such as
Image()
so useful).Yes, good catch! Updated!
Unfortunately this does not appear to be 100% reliable in chrome (i’m currently using version 62.0.3202.94, but this appears to have been an issue for a while), as sometimes contentWindow can still be null when onload is triggered.
This solution worked for me! Thanks a lot!
Thank you, saved me hours!
Sharry