3

I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:

$(function(){//document ready
$('some selector', frames['nameOfMyIframe'].document).doStuff()
});

However this doesn't seem to work. A bit of inspection shows me that the variables in frames['nameOfMyIframe'] are undefined unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get permission denied type errors).

Does anyone know of way to work around this?

I am L
  • 2,336
  • 2
  • 19
  • 35
  • 8
    It looks like you're getting bitten by the [Same Origin Policy](http://en.wikipedia.org/wiki/Same-origin_policy). – Frédéric Hamidi Oct 07 '13 at 13:01
  • Do you have control of the document in the iframe? – Gareth Oct 07 '13 at 13:01
  • 1
    If you're getting permission issues, I will assume that the iFrame's contents are in a domain that's different from the one where your own code is, right? If that's so you're trying to do something that, by design, can't be done. You'll have to look into *cross-domain Javascript* (see Hamidi's comment). Hope this helps you finding a direction to solve your problem. If both your page and the iFrame's contents are in the same domain, then disregard what I just said. – Geeky Guy Oct 07 '13 at 13:02
  • Maybe you are looking for [`.contents()`](http://api.jquery.com/contents/) ? – Brewal Oct 07 '13 at 13:05
  • so is there any way to do this? – I am L Oct 07 '13 at 13:12
  • exact duplicate of http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe – TheBrenny Feb 15 '16 at 06:42

2 Answers2

1

The only "workaround", if you can't make the other site include the relevant CORS headers, would be to fetch the iframe content server side and serve it as coming from your own domain.

The reason there isn't simpler workaround is due to why there is this same origin policy : to protect users.

you can not perform any access with cross domain iframe

Shakti Patel
  • 3,482
  • 4
  • 19
  • 27
0

As stated above, your issue is what is known as the "Same Origin Policy" which essentially is a scope-related problem. Communication between inherently separate html documents is not legal. There are, however, workarounds for the several occasions where iframe's residing on the same page can communicate with one another using the help of a third-party intermediary, check out this amazing solution for an example:

Resizing an iframe based on content

Community
  • 1
  • 1
Mike H.
  • 1,705
  • 9
  • 31