问题
Is there anything that prevents me from adding a event listener to the window that results from a window.open() call?
I am trying to set a handler function to be triggered on a visibility change event on the new document, but this handler function is not being called.
回答1:
There's nothing that prevents you from doing that (as long as the window you are opening is in the same domain as the parent/opener window; Just imagine what malicious people could do if that weren't the case).
Once you have the window
object of that new window, then you can do whatever you want to it. window.open()
returns the window
object of the new window:
// * All of this code is happening inside of the parent window,
// * but you can also 'inject' scripts into the new window if you wish.
// window.open() returns the new window's window object
var newWin = window.open('http://stackoverflow.com');
// Run all of your code onload, so you can manipulate the
// new window's DOM. Else, you're just manipulating an empty doc.
newWin.onload = function () {
// `this`, in this context, makes reference to the new window object
// You can use DOM methods, on the new document, with it.
var myElem = this.document.getElementById('custom-header');
console.log("Window object: ", this);
console.log("Window's location: ", this.location.href);
console.log("Id of element in new window: ", myElem.id);
// Attach a click event to the new document's body
this.document.body.onclick = function () {
// `this`, inside of a listener, is the element itself
// but this console.log will log inside of the parent window
console.log(this);
this.style.transition = 'all 1s';
this.style.opacity = 0;
};
this.document.body.addEventListener('click', function () {
// Now, let's log inside of the new window.
// Since in here, this === this.document.body,
// then you'll have to use the newWin var we set before.
// newWin is the window object.
newWin.console.log('Logging in new window!');
});
};
来源:https://stackoverflow.com/questions/30040441/javascript-add-event-listener-to-document-opened-in-new-window