Chrome 用户脚本错误:“不安全的 JavaScript 尝试访问框架”
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";
在此 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 脚本
相关文章:
- 从JavaScript访问struts操作中的属性
- 通过 javascript 访问类
- 如何使用JavaScript访问HTML链接内容
- 使用javascript访问php变量
- Javascript-访问对象
- 使用Oauth使用Javascript访问Api
- 通过JavaScript访问需要身份验证的页面
- 如何使用javascript访问sails.js模型中的属性
- 用javascript访问数组中的数组
- 从Symfony2中的javascript访问php变量
- 从Middleman中的Javascript访问config.rb
- 如何从javascript访问表单数据
- 创建一个html表单并使用javascript访问中的python脚本
- 使用JavaScript访问Chrome扩展的剪贴板
- 如何从javascript访问sqlite3数据库表值
- 如何从 JavaScript 访问 Sign Applelet 方法
- JavaScript:访问继承子模块中的“封闭”变量
- 使用 FourSquare API 和 javascript 访问场地提示
- 如何从javascript访问MySql数据库的数据
- 如何通过 javascript 访问参数化函数背后的代码