简体   繁体   中英

Cannot Add Event Listener

i can add an event listener for clicks to blank but not to twitter in the code below.

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"));

is it because twitter has done something to not let me do this? would there be a way to get around it?

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

The reason that you did not got any exception :

Most browsers don't support multiple popups so in order to accomplish it wou need to try using:

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

Or Give each window a new window name .

window.open(url, WindowName)

Security Risk

You can't add an event listner with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin .

Origin is considered different if at least one of the following parts of the address isn't maintained:

<protocol>://<hostname>:<port>/...

Protocol , hostname and port must be the same of your domain, if you want to access a frame.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

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 

Not recommended

Disabling same-origin policy in your browser

I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser . Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (eg development purposes) .

For security reasons browsers disable any interaction across domains that you do not own. Imagine all the things one could do with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM