【问题标题】:Add event listener to document opened in new window将事件侦听器添加到在新窗口中打开的文档中
【发布时间】:2015-07-14 10:44:17
【问题描述】:

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

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

【问题讨论】:

  • 您使用window.open() 打开的文档是否与您打开它的来源相同(例如,相同的域、端口和协议)?如果不是,则浏览器会限制您可以对跨源文档执行的操作,包括安装事件处理程序。

标签: javascript event-handling dom-events visibility


【解决方案1】:

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

【讨论】:

  • 那个新的window 对象仍然受到同源限制,所以如果它不是同一个域,那么你的答案中的第一句话是不正确的。
  • 哦,是的,我只是假设我们正在谈论从同一个域打开的窗口。感谢您指出这一点。
  • 不在同一个域中。那么我可以假设这可以解释为什么它不起作用吗?
  • 是的,据我所知,没有办法绕过这个限制......特别是如果您无法控制其他域。我想这个答案不是那么有用,所以如果没有更多的 cmets,我会稍微摆脱它。 :p
  • 哦,请不要摆脱它!这可能对处于另一种情况的人有所帮助!无论如何,谢谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 2020-05-17
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
相关资源
最近更新 更多