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

yel*_*int 4 javascript iframe greasemonkey google-chrome userscripts

// 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";
Run Code Online (Sandbox Code Playgroud)

在此脚本的用户脚本中运行: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.
Run Code Online (Sandbox Code Playgroud)

(我只是一个基本的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");
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 13

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

您可以在用户脚本中处理iframed内容,因为Chrome(和Firefox)处理iframe页面就像它们是主页一样.考虑到这一点,脚本编写这些页面非常容易.

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

<html>
<body>
    <iframe src="http://domain_B.com/SomePage.htm"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


如果你设置这样的@match指令:

// @match http://domain_A.com/*
// @match http://domain_B.com/*
Run Code Online (Sandbox Code Playgroud)

然后你的脚本将运行两次 - 一次在主页面上,一次在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");
}
Run Code Online (Sandbox Code Playgroud)

您将看到绿色的主页面和粉红色的iframed页面.


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

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




正如您所发现的(对另一个答案的评论),您可以在Chrome上禁用相同的原始政策.不要这样做! 你会让自己对坏人设置的各种诡计开放.除了邪恶的网站,许多名义上"好"的网站 - 允许用户发布内容 - 可能会潜在地跟踪,破解或欺骗你.