无法添加事件监听器

时间:2020-03-18 05:42:21

标签: javascript events onclick click event-listener

在下面的代码中,我可以为blank而非twitter的点击添加事件监听器。

const blank = window.open();
const twitter = window.open("https://twitter.com");

const PrintClick = function (name) {
    return function (...args) {
        console.log(name, ...args);
    };
};

blank.addEventListener("click", PrintClick("blank"));
twitter.addEventListener("click", PrintClick("twitter"));

是因为Twitter做了一些不允许我做的事情吗?有办法解决吗?

3 个答案:

答案 0 :(得分:0)

addEventListener只能监听当前页面的dom对象,可以考虑使用硒自动化框架操作

答案 1 :(得分:0)

您没有任何例外的原因:

大多数浏览器不支持多个弹出窗口,因此要完成此操作,您需要尝试使用:

window.open(yoururl,"_blank",'PopUp',randomnumber,'scrollbars=1,menubar=0,resizable=1,width=850,height=500');

或者给每个窗口一个new window name

window.open(url, WindowName)

安全风险

不能使用JavaScript添加具有不同来源的事件列表,如果可以的话,这将是一个巨大的安全漏洞。对于same-origin policy浏览器阻止试图访问具有不同来源的框架的脚本

如果未保留地址的以下至少其中之一,则认为来源不同:

<protocol>://<hostname>:<port>/...
如果要访问框架,

协议主机名端口必须与您的域相同。

示例

尝试从http://www.example.com/home/index.html

访问以下URL会发生以下情况
URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

不推荐

您的浏览器中禁用同源策略

我将链接相对答案。但是,请记住,禁用同源策略只会影响您的浏览器。此外,运行禁用了同源安全设置的浏览器会授予任何网站访问跨域资源的权限,因此这是非常不安全的,如果您不确定自己到底是什么,则绝对不要这样做做(例如出于开发目的)

答案 2 :(得分:0)

出于安全原因,浏览器会禁用您不拥有的域之间的任何交互。想象一下所有人可以做的所有事情。