我正在编写一个用于Firefox,Edge和Chrome的Web扩展,只使用通用代码(唯一的区别是顶级命名空间browser
vs chrome
),使用清单中的以下权限:
"permissions": [
"*://*/*",
"activeTab",
"storage",
"webRequest"
]
(域通配符是因为这需要为http和https页面启动)
我也有一个后台脚本main.js
:
var namespace = false;
if (typeof browser !== "undefined" && browser.browserAction) {
namespace = browser;
}
else if (typeof chrome !== "undefined" && chrome.browserAction) {
namespace = chrome;
}
if (namespace) {
namespace.browserAction.onClicked.addListener(e => {
namespace.tabs.executeScript({
file: `start.js`
});
});
} else {
throw new Error("This browser does not support the webextension 'browser' or 'chrome' namespace.");
}
然后是一系列导致start.js的content_script条目:
"content_scripts": [
{
"matches": [ "*://*/*" ],
"js": [
"vendor/base64.js",
"vendor/codemirror.js",
"vendor/html-beautify.js",
"vendor/md5.min.js",
"vendor/mode/css/css.js",
"vendor/mode/htmlmixed/htmlmixed.js",
"vendor/mode/javascript/javascript.js",
"vendor/mode/xml/xml.js",
"utilities.js",
"modal.js",
"listening.js",
"editor.js",
"publisher.js",
"help.js",
"pagemixer.js"
],
"css": [
"vendor/codemirror.css",
"pagemix.css"
]
}
]
通过此设置,Firefox允许我通过使用以下方式聚合当前选项卡的应用文档样式:
getPageStyle() {
let css = [];
Array.from(document.styleSheets).forEach(s => {
Array.from(s.cssRules).forEach(r => {
css.push(r.cssText);
});
});
return css.join('\n');
}
但是,在Chrome中会抛出一个CORS错误:
未捕获的DOMException:无法从'CSSStyleSheet'读取'cssRules'属性:无法访问规则
据我所知,我的权限说我的网络扩展应该“在任何地方”使用本地页面权限运行,因此CORS不应该在这里获取方式:如何设置此扩展与Chrome的完整DOM和CSSOM访问?
(根据我的发现,Cannot access cssRules from local css file in Chrome 64一般描述了“为什么”,但是网页扩展应该与页面一样运行,所以这应该没有额外的权限,但它没有)
在manifest.json上添加以下部分。
"web_accessible_resources": [
"vendor/*.js",
"*.js",
"vendor/*.css",
"*.css",
],
在https://developer.chrome.com/extensions/manifest/web_accessible_resources找到了解决方案