Chrome 用户脚本错误:“不安全的 JavaScript 尝试访问框架”

Chrome userscript error: "Unsafe JavaScript attempt to access frame"

本文关键字:JavaScript 访问 框架 不安全的 脚本错误 用户 不安全 Chrome      更新时间:2023-09-26
// 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";

在此 url 的用户脚本中运行:http://www.free-tv-video-online.me/player/sockshare.php?id=24DA6EAA2561FD60

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

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.

(我只是一个基本的Javascript用户(


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

// ==UserScript==
// @name       Resize
// @include    http://www.free-tv-video-online.me/player/sockshare.php*
// @include    http://www.sockshare.com/*
// ==/UserScript==
if (!(window.top === window.self)) {
    var player = document.getElementById('player');
    setSize(player);
}
function setSize(player) {
    player.style.setProperty("width", "1000px");
    player.style.setProperty("height", "650px");
}

出于安全原因,普通的javascript确实无法访问iframe内容,这是在不同的域上。 但是,这绝不会阻止Chrome,Tampermonkey或Greasemonkey中的用户脚本。

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

例如,假设您的页面位于domain_A.com

<html>
<body>
    <iframe src="http://domain_B.com/SomePage.htm"></iframe>
</body>
</html>


如果像这样设置 @match 指令:

// @match http://domain_A.com/*
// @match http://domain_B.com/*

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

所以如果你的脚本是这样的:

// ==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");
}

您将看到灰绿色的主页,粉红色的iframe页面。


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

if (window.top === window.self) {
    //--- Code to run when page is the main site...
}
else {
    //--- Code to run when page is in an iframe...
}




正如您发现的那样(根据对另一个答案的评论(,您可以在 Chrome 上禁用同源政策。别这样! 你会让自己对坏人设置的各种恶作剧敞开大门。 除了邪恶的网站之外,许多名义上的"好"网站 - 允许用户发布内容 - 可能会跟踪,黑客或欺骗你。

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

在此处查看最高答案:

jQuery 跨域 iframe 脚本