未捕获的安全错误:无法从“HTMLIFrameElement”读取“contentDocument”属性:阻止了源自“https://localhost”的框架。

20
我在尝试捕获G +关注按钮的点击事件时遇到以下问题。
未捕获的安全错误:无法从HTMLIFrameElement读取'contentDocument'属性:阻止了一个带有起源“https://localhost”的框架访问一个带有起源“https://apis.google.com”的框架。协议、域和端口必须匹配。

2个回答

5
我发现了一个类似的讨论,Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFram
当你尝试调用跨域的ajax时会出现此问题,请查看此文章以获取有关同源策略的更多信息。 Mozilla的同源策略文章 要解决此问题,您需要添加此代码。
document.domain = 'yourdomain.com'

从文章本身来看:

一个页面可以在一定限制下更改自己的来源。脚本可以将document.domain的值设置为当前域的子集。如果这样做,较短的域用于后续的来源检查。例如,假设位于http://store.company.com/dir/other.html的文档中的脚本执行以下语句:

document.domain = "company.com";

在执行该语句后,页面将通过http://company.com/dir/page.html的来源检查。然而,同样的道理,company.com不能将document.domain设置为othercompany.com。浏览器会单独保留端口号。任何对setter的调用,包括document.domain = document.domain,都会导致端口号被覆盖为null。因此,仅通过在第一个中设置document.domain =“company.com”无法使company.com:8080与company.com通信。必须在两个中都设置,以使端口号都为null。

21
我尝试了你的解决方案,但出现了以下信息:SecurityError: Failed to set the 'domain' property on 'Document': 'http://mimouni.info' 不是 'localhost' 的后缀。 - Mimouni

0
我的解决方案可以在Angular中重建iframe并且可用。当我们构建一个iframe时,需要进行源安全检查以修改iframe内容。这个解决方案允许我们多次重新创建iframe内容。

HTML

<div id="iframecontainer"></div>

JS

var content = "<h1>Content inside Iframe</h1>"; //desired content of iframe
var iframecontainer = document.getElementById("iframecontainer");
iframecontainer.innerHTML ='<iframe id="threedsframe" width="%90" height="400px"></iframe>';
var iframe = iframecontainer.childNodes[0];
let doc =  iframe.contentDocument || iframe.contentWindow;
doc.open();
doc.write(content);
doc.close();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接