Issue
Due to how some of our pages work, JS can get injected into the page at any point and sometimes this JS closes the current window. The problem is that I need to attach an event listener to the onunload of the window so that a value may be returned from the window to the parent page. But because the window close script may be injected at any point, I can't bind this event to the onload due to how it works so I was hoping to use DOMContentLoaded since that event will trigger before the injected script does.
However in my tests, I cannot get anything to bind to DOMContentLoaded on the parent page where the new window is being created.
Here is an what I am currently working with: Plunker
We only need this to work in Chrome at the moment.
Our current method of doing this works like this (pseudocode):
onButtonClick = function(){
win = window.open(...);
win.onload = function(){
win.onunload = function(){
//Bind some function that will get the window's "return value" and pass it to the parent page
//This will never happen if the window closes itself before the page is done loading
};
};
};
Can I use DOMContentLoaded to accomplish what I want? If so, how do I properly attach it to the window?
Note: I cannot bind the onunload event directly to the window once it is created. It seems to fire the onunload event twice (once when the window opens and once when it closes). You can see this happening if you use the bindOnCreate function in my example.
Solution
If you change line 58 from
w.document.addEventListener('DOMContentLoaded', ...)
to
w.addEventListener('DOMContentLoaded', ...)
it works. I'll try to explain what's actually going on under the hood:
- When window is opened, it is initially having URL
about:blank. You can check this by loggingw.location.toString()inonunloadevent handler (see next step). - Immediately after that the browser loads URL supplied in
window.open, thus triggeringonunloadforabout:blank(first time). - Real page with different window.document is loaded into pop-up window, but your event handlers are still listening to the DOM root of
about:blankpage because you added events towindow.document, notwindow; and right now as we have another URL loaded,window.documentis completely different object than one step before. - When you close window,
onunloadis triggered again (second time) because youronunloadevent was connected to window.
If you addEventListener for pop-up's window, it receives events from all window.document-s that will be loaded inside that window because of JS event bubbling mechanism.
I hope this answers your questions.
Answered By - Andrew Dunai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.