Chrome用户脚本错误:";不安全的JavaScript试图访问帧“;

Chrome用户脚本错误:";不安全的JavaScript试图访问帧“;,javascript,google-chrome,iframe,greasemonkey,userscripts,Javascript,Google Chrome,Iframe,Greasemonkey,Userscripts,在此url的用户脚本中运行: 为什么Chrome会出现此错误并使脚本失败?: // the iframe of the div I need to access var iframe = document.getElementsByTagName("iframe")[2]; var innerDoc = iframe.contentDocument || iframe.contentWindow.document; // resize 'player' in the iframe innerD

在此url的用户脚本中运行:

为什么Chrome会出现此错误并使脚本失败?:

// the iframe of the div I need to access
var iframe = document.getElementsByTagName("iframe")[2];
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

// resize 'player' in the iframe
innerDoc.getElementById('player').width = "1000px";
innerDoc.getElementById('player').height = "650px";
(我只是一个基本的Javascript用户)


最后的代码,非常感谢回答者:

Unsafe JavaScript attempt to access frame with URL http://www.sockshare.com/embed/24DA6EAA2561FD60 
from frame with URL http://www.free-tv-video-online.me/player/sockshare.php?id=24DA6EAA2561FD60. 
Domains, protocols and ports must match.

出于安全原因,您的浏览器不允许您从另一个域访问iframe中的javascript

请参见此处的顶部答案:


出于安全原因,普通javascript确实无法访问不同域上的iframe内容然而,这并不能阻止Chrome、Tampermonkey或Greasemonkey中的用户脚本

您可以在用户脚本中处理iframe内容,因为Chrome(和Firefox)处理iframe页面就像处理主页一样。考虑到这一点,编写这样的页面很容易

例如,假设您在域A.com上有此页面:

然后脚本将运行两次——一次在主页上,一次在iframe上,就像它是一个独立的页面一样

如果你的脚本是这样的:

<html>
<body>
    <iframe src="http://domain_B.com/SomePage.htm"></iframe>
</body>
</html>
// @match http://domain_A.com/*
// @match http://domain_B.com/*
// ==UserScript==
// @name  _Test iFrame processing in Chrome and Tampermonkey
// @match http://domain_A.com/*
// @match http://domain_B.com/*
// ==/UserScript==

if (/domain_A\.com/i.test (document.location.href) ) {
    //Main page
    document.body.style.setProperty ("background", "lime", "important");
}
else {
    //iFrame
    document.body.style.setProperty ("background", "pink", "important");
}
您将看到灰绿色的主页,以及粉红色的iframed页面


或者,您可以这样进行测试:

<html>
<body>
    <iframe src="http://domain_B.com/SomePage.htm"></iframe>
</body>
</html>
// @match http://domain_A.com/*
// @match http://domain_B.com/*
// ==UserScript==
// @name  _Test iFrame processing in Chrome and Tampermonkey
// @match http://domain_A.com/*
// @match http://domain_B.com/*
// ==/UserScript==

if (/domain_A\.com/i.test (document.location.href) ) {
    //Main page
    document.body.style.setProperty ("background", "lime", "important");
}
else {
    //iFrame
    document.body.style.setProperty ("background", "pink", "important");
}




正如您所发现的(根据对另一个答案的评论),您可以不要这样做你会让自己面对坏人的各种恶作剧。除了邪恶的网站,许多名义上的“好”网站——允许用户发布内容——可能会跟踪、攻击或欺骗你。

哦,我明白了。我误解了错误(以及其他解释)。您以某种方式使其更易于理解:)-找到了禁用该安全选项的方法:)不希望您的用户这样做,是吗?这个答案对于用户脚本不正确。他们有一种机制可以绕过这个跨域限制,并且不会影响安全性。罗得西亚,正如我所说的,对于一个用户来说,哇,这非常有效。把我最后的代码放在OP里,谢谢你!