[英]Facebook gives “Unsafe JavaScript attempt to access frame with URL” error in Chrome
[英]Chrome userscript error: “Unsafe JavaScript attempt to access frame”
// 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";
在此脚本的用户脚本中运行: 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...
}
正如您所发现的(对另一个答案的评论),您可以在Chrome上禁用相同的原始政策 。 不要这样做! 你会让自己对坏人设置的各种诡计开放。 除了邪恶的网站,许多名义上“好”的网站 - 允许用户发布内容 - 可能会潜在地跟踪,破解或欺骗你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.