开发者

Trouble with iframes

I'm generating iframes dynamically for a lot of different random websites, and I tend to get this error in my javascript console (not necessarily with this url):

Unsafe JavaScript attempt to access frame with URL http://localhost:3000/results/ from frame with URL http://www.apple.com/iphone/. Domains, protocols and ports must match.

Why am I getting this error? Is there a way to get rid of it?

So the only two times I interact with iframes in javascript is when I dynamically load in an iframe:

$("#results_div").html('<开发者_运维百科;iframe src='+url+' frameborder="0" class="iframe"><p>Browser does not support iframes.</p></iframe>');

and when I pull the src attribute of an iframe:

var previewed = $("iframe").attr("src");

Which one is causing the error?


Script in your iframe is trying to access parent's script/dom and they are in different domains. Cross domain scripting genrally generates that error.

In your case, apple.com and localhost are different domains and something in those iframe is trying to access its parent window's script or dom element.

Couple of ways to solve this:

  • Make sure both belong to same domain: http://www.google.com/url?sa=t&source=web&cd=2&ved=0CD0QFjAB&url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen%2FSame_origin_policy_for_JavaScript&ei=VHsaTtqtGcPngQeLvN31Dw&usg=AFQjCNF2yi5TJQGfSywsrfxVvKdsQYzIKg
  • Limited: Use HTML5's cross domain messaging via postmessage: http://ajaxian.com/archives/cross-window-messaging-with-html-5-postmessage
  • Limited: Use JOSNP calls: http://www.zackgrossbart.com/hackito/jsonp-sop/


This is due to the fact that your script is trying to acces some code on another domain. This behaviour can be understood by reading Same origin Policy. http://en.wikipedia.org/wiki/Same_origin_policy

There are workarounds and some implementation by which you can resolve this issue.

Some of them are using proxy approach, Fragment identifier approach.

In HTML5 we can use postmessages to get this resolved.

But you have to figure out what may work for you.


You cannot interact with a different domain with javascript or iframes apart from loading the domain with the into the iframe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜