Javascript windowopen observing when a window already exists using Prototype
I ran into an odd scenario where window.open () does not fire a "load" event if the actual window is already on the screen.
Summary
I have a button that, when clicked, runs some javascript and opens the page in a new window. Standard code that any JS developer has seen. When a method (part of a larger class) is called, it checks to see if it has a reference to the window (this.preview_window). If so, it will run this.up, it will try to open it again. Once it is open, it launches the update method on this window.
Problem
If the window does not exist, everything works as expected. If the window exists, but the class does not have a reference to it, then the reference is successfully obtained using window.open (), but the update function is not called.
Corresponding 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 pretty much, so I'm pretty sure I'm missing something about how the load event works. The window.open () and update () functions work as expected in all cases except this one.
a source to share
I've experimented a bit with this and it seems the problem is what the previous answer was talking about - if you already have a window, then calling window.open () won't fire the load event. Therefore, you need to update the preview window every time the event handler for your button is called to make sure the load event is fired and therefore your update handler can also be called. Here's 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>
It might not be very exciting, but hopefully it puts you on a more promising path.
a source to share
I am assuming that either the child window is on a different domain when the binding occurs, or it is loaded from the cache before the load happens. try putting your binding on a 500ms timeout. If you are manipulating the url of the child window, it would be easier to call the parent from the child. Alternatively close and reopen.
if (this.preview_window && !this.preview_window.closed)
this.preview_window.close();
... open window ...
a source to share