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

标签 javascript event-handling dom-events visibility

有什么东西阻止我向 window.open() 调用产生的窗口添加事件监听器吗?

我正在尝试将处理函数设置为在新文档的可见性更改事件上触发,但未调用此处理函数。

最佳答案

没有什么可以阻止您这样做(只要您打开的窗口与父/开启窗口在同一个域中;想象一下,如果不是这种情况,恶意人员会做什么)。 一旦你有了新窗口的 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!');
    });
};

关于javascript - 将事件监听器添加到在新窗口中打开的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040441/

相关文章:

javascript - 页面加载一段时间后下载文件?

javascript - jQuery Flot - 四舍五入 x 轴值?

asp.net - 哪些 .NET 控件不使用 javascript 来处理事件?

javascript - FireFox Javascript 事件处理

javascript - 提交按钮的事件触发顺序

Javascript:ReferenceError:未定义 MyClass

JavaScript:一页上有两个 "I agree to terms checkboxes"

c++ - 有什么办法可以捕捉到 window 晃动吗?

javascript - EmberView 'keydown' 和 'keypress' 事件不渲染?

javascript - window.scroll() 函数未触发