Javascript:将事件侦听器添加到新窗口中打开的文档

Javascript:将事件侦听器添加到新窗口中打开的文档,javascript,javascript-events,event-handling,visibility,Javascript,Javascript Events,Event Handling,Visibility,是否有任何东西阻止我将事件侦听器添加到由window.open调用生成的窗口 我正在尝试设置一个处理程序函数,以便在新文档的可见性更改事件中触发,但未调用此处理程序函数。只要您打开的窗口与父窗口/打开器窗口位于同一域中,就没有任何东西阻止您这样做;想象一下,如果不是这样,恶意的人会做什么。 一旦你有了新窗口的窗口对象,你可以做任何你想做的事情。window.open返回新窗口的窗口对象: // * All of this code is happening inside of the paren

是否有任何东西阻止我将事件侦听器添加到由window.open调用生成的窗口


我正在尝试设置一个处理程序函数,以便在新文档的可见性更改事件中触发,但未调用此处理程序函数。

只要您打开的窗口与父窗口/打开器窗口位于同一域中,就没有任何东西阻止您这样做;想象一下,如果不是这样,恶意的人会做什么。 一旦你有了新窗口的窗口对象,你可以做任何你想做的事情。window.open返回新窗口的窗口对象:

// * 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!');
    });
};

新的窗口对象仍然受到相同来源的限制,因此如果它不是同一个域,那么您回答中的第一句话是不正确的。哦,是的,我只是假设我们讨论的是从同一个域打开的窗口。谢谢你指出这一点。它不在同一个域中。所以我可以假设这可以解释为什么它不起作用吗?是的,就我所知,没有办法绕过这个限制。。。特别是如果你无法控制其他领域。我猜这个答案没有那么有用,所以如果没有进一步的评论,我会在一点时间内把它去掉波赫,请不要把它扔掉!在另一种情况下,它可能会对某人有所帮助!无论如何,感谢您的帮助:您正在使用Windows打开的文档是否与您正在打开的文档具有相同的来源,例如相同的域、端口和协议?如果没有,则浏览器将限制您可以对跨源文档执行的操作,包括安装事件处理程序。