Mar 06 2009

Detecting Document Loaded on Window.Open()

Published by at 12:35 am under General

One of the tasks I have to achieve in a CRM project I’m working on requires opening a new IE window and identifying when the document within it has been loaded.

Unfortunately I have been unable to find a solution to this online but  found plenty of references to methods that don’t work.  So I decided to play around until I found a method that work and blog about it…. I guess I succeeded as you’re reading this!

Creating a new window using JavaScript is easy enough:

<script language="javascript">
    var newWindow = window.open("popup.html", "new popup window");
</script>

What would be really useful is if you could attach to an onload event of the newWindow variable.  Unfortunately this isn’t possible.  What I have found out is that it is possible to call back from the popup window to the code that loaded it.

For example, if we have two pages index.html and popup.html we can add the following code to index.html:

<script language="javascript">
    window.open("popup.html", "new popup window");
 
    function popupLoaded(newWindow)
    {
        // code to run after popup has loaded
    }
</script>

Within popup.html we can then added the following which will call back to the popupLoaded function in index.html when the popup is loaded:

<script language="javascript">
    function callback() {    
        window.opener.popupLoaded(this);
    }
</script>
<body onload=?callback()?>
</body>

The reason for the inclusion of the newWindow parameter of popupLoaded is to be able to get a handle on the new popup window.  I tried using a object returned from window.open() but it didn’t seem to keep a valid handle to the popup window.

kick it on DotNetKicks.com

2 responses so far