Add event listener to document opened in new window(将事件侦听器添加到在新窗口中打开的文档中)
问题描述
是否有任何事情阻止我将事件侦听器添加到由 window.open()
调用产生的窗口中?
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.
推荐答案
没有什么可以阻止你这样做(只要你打开的窗口与父/打开器窗口在同一个域中;只是想象一下,如果不是这种情况,恶意的人会做什么).一旦你有了那个新窗口的 window
对象,你就可以对它做任何你想做的事情.window.open()
返回新窗口的window
对象:
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!');
});
};
这篇关于将事件侦听器添加到在新窗口中打开的文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将事件侦听器添加到在新窗口中打开的文档中


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01