问题
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?
回答1:
addEventListener can only listen to the dom object of the current page, you can consider selenium automation framework operations
回答2:
For security reasons browsers disable any interaction across domains that you do not own. Imagine all the things one could do with that.
回答3:
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 (e.g. development purposes).
- Google Chrome
- Mozilla Firefox
- Safari
- Opera
- Microsoft Edge: not possible
- Microsoft Internet Explorer
来源:https://stackoverflow.com/questions/60734092/cannot-add-event-listener