Search code examples
javascriptprototypejs

Javascript window.open observation when window already exists using Prototype


I've come across an odd scenario in which window.open() is not triggering the 'load' event if the actual window is already on the screen.

Synopsis
I have a button that when clicked runs some javascript and opens a page in a new window. Standard code that any JS developer has seen. When the method (part of a larger class) is called, it checks if it has a reference to the window (this.preview_window). If so, it will run this.up, it will try and open it again. Once it is open, it runs an update method on that window.

Problem
If the window does not exist, everything runs as expected. If the window does exist but the class doesn't have a reference to it, then the reference is successfully acquired with window.open(), however the update function doesn't get called.

Relevant Code

// This code is run whenever there is no reference to the window
this.preview_window = window.open('/folder/page.php','page_previewer');
Event.observe(this.preview_window, 'load',this.update.bindAsEventListener(this));

The rest of the code has been tested heavily so I'm fairly confident that I'm missing something in how the load event works. The window.open() and update() functions operate as expected in all cases but this one.


Solution

  • I experimented with this a little bit and it seems the problem is something the previous answer had alluded to - if you already have a window open the call to window.open() will not fire the load event. Therefore, you essentially need to refresh the preview window every time the event handler for your button is called in order to make sure that the load event will be fired and therefore your update handler can also be called. Here is the code I used to demonstrate this:

    var preview_window;
    
    function openPreviewWindow() {
        if (preview_window) {
            preview_window.close(); //Load will not fire unless we close the window first
        }
        preview_window = window.open('/', 'preview_window');
        Event.observe(preview_window, 'load', function () {
            alert('Updating opened window.');
        }.bindAsEventListener(this));
    }
    
    <a href="#" onclick="openPreviewWindow()">Open Preview Window</a>
    

    This may not be terribly enlightening but hopefully it sets you on a more promising path.