【发布时间】:2016-09-24 21:40:12
【问题描述】:
目标:我想开发一个 Firefox Web 扩展(类似于 Chrome 扩展),它可以在加载 HTML 和 JavaScript 文件之前检测它们。如果这些文件中有特定内容,则将其屏蔽,否则允许通过。
问题:无法收集具有不同域的文件内容,因为它们会抛出“Cross-Origin”错误,因为缺少Access-Control-Allow-Origin标头。
我阅读了很多关于这个问题的资料,并且文档说,如果在 Webextension 清单中设置了权限,则不需要 Access-Control-Allow-Origin 标头。这里引用Mozilla Doc:
使用权限键为您的扩展请求特殊权限。 [...] 密钥可以包含三种权限: [...] 主机 权限 [...] 主机权限被指定为匹配模式, 并且每个模式都标识了一组 URL 的扩展是 请求额外的特权。额外权限包括:XHR 访问权限 那些起源 [...]
我的 manifest.json:
{
[...],
"permissions": [
"tabs",
"*://*/*",
"webRequest",
"webRequestBlocking",
"<all_urls>"
],
"background": {
"scripts": ["backgroundscript.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["/lib/jquery-2.2.4.min.js", "/contentscript.js"],
"run_at": "document_start"
}
]
}
这里,我的权限键中有"*://*/*",是什么意思,每个网络资源都应该有权限,不应该出现跨域错误?还是我错了?谁能告诉我,为什么我会收到错误或如何避免它?
我的背景脚本.js:
chrome.webRequest.onBeforeRequest.addListener(
logURL,
{urls: ["<all_urls>"], types: ["main_frame", "script"]},
["blocking"]
);
function logURL(requestDetails) {
chrome.tabs.sendMessage(
requestDetails.tabId,
{action: "getContentByURL", url: requestDetails.url, type: requestDetails.type},
function(response) {
console.log(response);
}
);
if(requestDetails.type == 'script') {
// here will be the conditions, based on the content of the files,
// if they will be canceled or allowed to pass
// actually, there is just a dummy "false"
return {cancel: false};
}
}
我的 contentscript.js:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
var contentAll = [];
if(message.action == 'getContentByURL') {
var pageContent = getContentByURL(message.url);
contentAll.push(pageContent);
sendResponse({"content" : contentAll});
}
}
);
function getContentByURL(url) {
$(document).ready(function() {
$.get(url, function(data) {
console.log(data);
});
});
}
在 contentscript.js 中,我使用 jQuery $.get 方法来访问网站内容。我还尝试了 $.ajax 与 dataType jsonp,但在这种情况下,我得到了一个无限的访问链,并且脚本尝试无限次加载资源。我完全不明白,为什么会这样,可能是因为我使用了chrome.webRequest.onBeforeRequest监听器,如果有新的连接就会被访问,而在这种情况下它会陷入死循环?
在我阅读的Mozilla Doc 中,chrome.webRequest.onBeforeRequest 有一个参数,requestBody:
包含 HTTP 请求正文数据。 [...] 1. Firefox 不支持“requestBody”选项。
- 这个解决方案是最好的 => 但它不可用
- 我用权限模式尝试了 $.get => 我得到了 Cross-Origin 错误
- 我尝试了 $.ajax 与 jsonp 和相同的权限模式 => 我得到了无限循环
所以问题又来了:我怎样才能访问不同域的文件内容而不会出现跨域错误,其中域名是打开的(模式如“*://*/ *")?
【问题讨论】:
-
我遇到了同样的问题。我确实找到了这个页面developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/…,它讨论了 package.json 和一个名为 cross-domain-content 的特定“权限”键,但还没有弄清楚它与 manifest.json 之间的关系。
-
@Sharun 这是关于 Firefox Add-On 模型,而不是 WebExtensions 模型。
-
您的权限配置正确;这不应导致内容脚本代码出现 CORS 错误。请注意,您的
getContentByURL不会返回任何内容,因为get是异步的。 -
@Xan ya 刚刚意识到了不同之处。扩展 Noob 在这里。每次我查找某些内容时,我都会得到附加组件的文档和代码,这会引起一些混乱。现在工作。缺少 / 是罪魁祸首。
-
@Xan 你是对的,我删除了它。但这并没有影响 Cross-Origin 错误。我用 XMLHttpRequest 对象修复了它,而不是使用 jQuery 方法。也许它比 jQuery 更“深入”?
标签: javascript google-chrome-extension xmlhttprequest cross-domain firefox-addon-webextensions