我正在为许多不同的随机网站动态生成 iframe,并且我倾向于在我的 javascript 控制台中收到此错误(不一定使用此 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.
为什么会出现此错误?有办法摆脱它吗?
所以我在 javascript 中与 iframe 交互的唯一两次是在动态加载 iframe 时:
$("#results_div").html('<iframe src='+url+' frameborder="0" class="iframe"><p>Browser does not support iframes.</p></iframe>');
当我拉取 iframe 的 src
属性时:
var previewed = $("iframe").attr("src");
是哪个导致了错误?
最佳答案
您的 iframe 中的脚本正在尝试访问父级的脚本/dom,并且它们位于不同的域中。跨域脚本通常会产生该错误。
在您的情况下,apple.com
和 localhost
是不同的域,并且这些 iframe 中的某些内容正在尝试访问其父窗口的脚本或 dom 元素。
解决这个问题的几种方法:
- 确保两者属于同一个域: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
- 受限:通过
postmessage
使用 HTML5 的跨域消息传递:http://ajaxian.com/archives/cross-window-messaging-with-html-5-postmessage - 受限:使用 JOSNP 调用:http://www.zackgrossbart.com/hackito/jsonp-sop/
关于javascript - iframe 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6645708/