Creating a cross browser compatible solution based on parent/child-window communication is surprisingly difficult (because of Microsoft, I wish IE would die already). This situation arises when using window.open, which returns a reference to the child window. Limited events are available from parent to child, due to security concerns, but for the most part it isn’t difficult to connect to window onblur, onfocus, and other events.
Something like:
var win = window.open("my/file"); win.onload = function(){ // Do something }
would work in just about all browsers (Safari doesn’t open the window without an event for security, and IE just doesn’t work).
Accessing Parent Window Functions
Accessing parent scripts is easy since that wouldn’t create a security issue. Any code can be accessed like this:
var parent = window.opener; parent.globalFunction();
IE child window onload & running scripts on child windows
So what about IE? And what if we want to run scripts in the child window? Both are possible but require a little bit of gymnastics to accomplish. First the reason IE doesn’t allow you to connect to the onload event isn’t because it can’t be connected to, it’s because window.open may return before the window has actually been created. Any manipulation will subsequently give you an error telling you the window you’re working with is “null or not defined”. Instead you have to use setTimeout. The example below includes both that technique as well as a technique for injecting javascript in the child which works on all browsers:
var win = window.open('example.html'); var body; function ieLoaded(){ body = win.document.getElementsByTagName("body"); if(body[0]==null){ // Page isn't ready yet! setTimeout(ieLoaded, 10); }else{ // Here you can inject javascript if you like var n = win.document.createElement("script"); n.src = "injectableScript.js"; body.appendChild(n); } } ieLoaded();