【问题标题】:Cross origin security error although the iframe is on the same domain尽管 iframe 在同一个域中,但跨域安全错误
【发布时间】:2014-07-20 01:22:07
【问题描述】:

单击按钮时,控制台出现安全错误:

<iframe src="http://www.example.com/" id="iframe"></iframe>
<input type="button" value="Color it!" id="button">
<script>
    var iframe = document.getElementById('iframe'),
        button = document.getElementById('button');
    button.onclick = function () {
        iframe.src = 'linked-frame.html';
        iframe.contentDocument.body.style.background = 'red';
    };
</script>

DEMO

当我更改函数中的iframe 源时,它不应该抛出这样的错误。

【问题讨论】:

  • Blocked a frame with origin "http://dl.dropboxusercontent.com" from accessing a frame with origin "http://www.example.com". -- 那个“同一个域”怎么样?
  • 是的,这正是我在 Chrome 中收到的错误消息。但它不应该抛出这样的错误,因为我在我的函数中更改了 iframe 源。

标签: javascript html iframe same-origin-policy


【解决方案1】:

您不能简单地挂钩到 iframe 对象,这是不允许的。你可以添加一个seamless 属性来明确允许这种行为,然后让你的JavaScript适应它:

// old syntax, can’t work
iframe.contentDocument.body.style.background
// new syntax, seamless attribute required:
frame.style.background = 'red';

然后它会工作,但be aware of the browser support for seamless attribute

【讨论】:

  • 这无济于事:iframe 内容主体背景颜色与 iframe 元素背景颜色不同。要了解我的意思,比较 iframe.contentDocument.body.style.border = '1px solid red';iframe.style.border = '1px solid red';
  • 哦,刚刚又看了一遍。你没有在 dl.dropboxusercontent.com 上设置 CORS 规则(你不能顺便说一句),所以不允许以这种方式访问​​内容。 You could use a tool like iframe-resizer 您需要同时访问远程嵌入式服务器和本地服务器。
【解决方案2】:

您的问题是您需要等到 iframe 在更改 src 后加载,然后才能触发您的函数。

试试

var iframe = document.getElementById('iframe'),
button = document.getElementById('button');
button.onclick = function () {
  iframe.src = 'linked-frame.html';

  iframe.onload = function() {
    iframe.contentDocument.body.style.background = 'red';
  };

};

例子在这里http://jsfiddle.net/vrTP9/1/

【讨论】:

  • 感谢您的回答!但如果单击红色 iframe 内的链接,它会给出相同的错误消息:Demo
猜你喜欢
  • 2010-10-25
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2013-02-26
  • 2010-09-30
  • 1970-01-01
  • 2010-11-23
相关资源
最近更新 更多