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

Iza*_*ela 8 javascript visibility event-handling dom-events

是否有什么因素阻止我向调用产生的窗口添加事件侦听器window.open()

我试图设置一个处理程序函数,以在新文档上的可见性更改事件上触发,但该处理程序函数没有被调用。

小智 7

没有什么可以阻止您这样做(只要您打开的窗口与父/打开窗口位于同一域中;想象一下,如果不是这种情况,恶意人员会做什么)。一旦你有了window新窗口的对象,你就可以对它做任何你想做的事情。window.open()返回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!');
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 哦,请不要摆脱它!这可能对处于其他情况的人有帮助!不管怎样,谢谢你的帮助:) (4认同)