// 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 中的用户脚本。
您可以在用户脚本中处理 iframed 内容,因为 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");
}
您会看到浅绿色的主页和粉红色的 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...
}
正如您发现的(根据对另一个答案的评论),您可以 disable the same origin policy on Chrome . 不要这样做!您会让自己暴露在坏人设下的各种诡计面前。除了邪恶网站之外,许多名义上的“好”网站(允许用户发布内容)也可能会跟踪、入侵或欺骗您。
关于javascript - Chrome 用户脚本错误 : "Unsafe JavaScript attempt to access frame",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10666258/