上周左右我一直在阅读和使用 Chrome 扩展,但我在尝试实现我想要的东西时遇到了困难。我想要创建的是一个扩展,它在后台(或默默地)访问网站,在网页上填写表格并检索响应。该网站没有 API,我无法创建服务器来执行此操作,因为该网站每小时只允许每个 IP 发出 X 个请求,因此我的请求在几个用户之后就会耗尽。
所以我的想法是创建一个后台页面,其中包含一些 javascript,使用 JS 来填写表单以 getElementById、设置值、提交表单并将响应无缝地返回给用户。
经过测试后,似乎同源政策阻止了我。这是我的代码:
_
清单.json
{
"manifest_version": 2,
"name": "Getting started example",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"permissions": [
"activeTab", "webRequest", "webRequestBlocking",
"https://ajax.googleapis.com/"
],
"background": {
"page": "Page.html"
}
}
页面.HTML:
<html>
<head>
<script src="myJS.js"></script>
</head>
<body>
<iframe src="CO-TEST-FRAME.html" width="400" height="400" id="maniframe" class="maniframe"></iframe>
<iframe src="http://www.myserver.com/iframe/CO-TEST-FRAME.html" width="400" height="400" id="maniframe2" class="maniframe2"></iframe>
<p id="test">new</div>
</body>
</html>
联合测试框架.HTML:
<html>
<head>
</head>
<body>
<div id="desired" class="desired" hidden="hidden">some text</div>
</body>
</html>
myJS.js:
window.onload = function() {
alert("working");
var iframe = document.getElementById("maniframe");
var iframeStuff = iframe.contentDocument || iframe.contentWindow.document;
var test = iframeStuff.getElementById("desired").innerHTML;
var iframe2 = document.getElementById("maniframe2");
var iframeStuff2 = iframe2.contentDocument || iframe.contentWindow.document;
var test2 = iframeStuff.getElementById("desired").innerHTML;
console.log(test);
console.log(test2);
}
当第 9、10、11、14 行被注释掉时,我按预期得到“Some Text”,即本地框架工作正常。但是,当我取消注释这些行时,第二帧(在服务器上)会抛出以下错误
myJS.js:10 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "chrome-extension://laocffdoafnoeipdndafcdbiaaephcah" from accessing a frame with origin "http://www.myserver.com". The frame requesting access has a protocol of "chrome-extension", the frame being accessed has a protocol of "http". Protocols must match.
我明白为什么这会被阻止(因为人们能够恶意运行 JS),但据我所知,后台页面是在隔离的环境中运行的,因此所有风险都得到了缓解?有没有办法绕过同源政策或以其他方式实现我想要实现的目标?可能在用户页面上有内容脚本和 1x1 iframe?