0

I'm just trying to pull an image from a site (not necessarily Bing but the problem is with every site it seems).
Running this code it seems to have failed at the 'if' statement. This makes me think there is no document.
I've been trying to figure out why this won't work but with my limited HTML/Javascript knowledge I just can't. Can someone enlighten me please.

I wouldn't need this many variables normally but in order to figure out the problem I made this code. I've also tried window.frames[0].document with no luck.

HTML:
<iframe id="test" src="https://www.bing.com/images/search?q=test"></iframe> <button onclick="myFunciton()">Go</button>

Javascript:

function myFunction() {
var x = document.getElementById("test");
var y = (x.contentWindow || x.contentDocument);
if (y.document){y = y.document;}
var test = y.getElementsByTagName("img")[0].src;
}
Alex
  • 1
  • 1
  • 1

2 Answers2

0

The problem is not with your if statement. For me, your code gives me back an error:

SecurityError: Blocked a frame with origin "https://www.example.com" from accessing a frame with origin "https://www.bing.com". Protocols, domains, and ports must match. 

Which means that you simply cannot access an iframe with different origins, otherwise it would be a huge security issue. The only way of interacting between iframes is using window.postMessage which you can read about in another post on StackOverflow.

squancy
  • 545
  • 1
  • 5
  • 24
0

You should be able to access iframe content by using following:

parent.ifr.document.getElementById('<some id>');

where ifr is the name or id of iframe window.

Please, also mind the cross-domain issues.

Thevs
  • 3,105
  • 2
  • 19
  • 31