I am trying to query elements in another window (different domain), opened from my site. For example, I might have a link like this:
<a href="#" onclick=openOtherWindow();>Click me</a>
Which runs code like this:
function openOtherWindow() {
var w = window.open("http://www.example.com/", "my_popup","height=500, width=800 left=20, top=40");
console.log('Left:' + w.screenLeft);
console.log('Num anchors: ' + w.document.anchors.length);
console.log('Num images: ' + w.document.images.length);
w.close();
}
The window opens, and the console shows:
Left: 20
Num anchors: 0
Num images: 0
(Yes, there are links and images). So, I figured maybe the window hadn’t actually loaded, so tried something like:
function openOtherWindow() {
var w = window.open("http://www.example.com/", "my_popup","height=500, width=800 left=20, top=40");
w.onload = function() {
console.log('Left:' + w.screenLeft);
console.log('Num anchors: ' + w.document.anchors.length);
console.log('Num images: ' + w.document.images.length);
}
w.close();
}
And now I am getting nothing in the console. I tried other ways of seeing what’s going on (replace console.log() with alert()) but no go.
I think I have a fundamental misunderstanding of how to know when the other window is open and loaded. Can anyone de-confuse me?
If the domain is different, you cannot access most (if not all) properties of the new window. This is called same-origin policy and it’s for security reasons.
For example, imagine that you register on a website and they send you an activation code by mail. Out of “courtesy”, they provide a link to GMail, Hotmail, Yahoo Mail and maybe a few other popular email providers. If they could access the contents from the new window, they could easily read your password when you type it in.
Further information:
Same origin policy for JavaScript – MDN
Same origin policy – Wikipedia