我试图在Firefox中编写一个简单的扩展,其中我修改了 X-Frame-Allow
标头 .
我简要地查看了文档,我发现它们支持 webRequest.onHeadersReceived.addListener()
. 但是,当收到 Headers 时,我无法让我的代码运行 .
manifest.json
{
"manifest_version": 2,
"name": "xframeoptions",
"version": "1.0",
"description": "Set X-Frame-Options to ALLOW",
"icons": {
"48": "icons/icon.png"
},
"permissions": [
"webRequest",
"webRequestBlocking",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["xframeoptions.js"]
}
]
}
xframeoptions.js
function rewriteHeader(e) {
console.log(e.responseHeaders);
for (var header of e.responseHeaders) {
console.log(header.name + ":" + header.value);
if (header.name == "X-Frame-Options") {
header.value = 'ALLOW';
modified = true;
break;
}
}
return {responseHeaders: e.responseHeaders};
}
console.log("Initializing xframeoptions extension ...test");
browser.webRequest.onHeadersReceived.addListener(
rewriteHeader,
{urls: ['<all_urls>']},
["blocking", "responseHeaders"]
);
如何通过Firefox的WebExtensions修改响应标头?
1 回答
内容脚本无法访问您正在使用的API
您正试图从content script执行此操作 . 你需要从background script这样做 . 内容脚本可以访问WebExtensions API的一小部分 . 可用的API包括(来自MDN Content Scripts page):
这不包括您尝试使用的API(例如webRequest) .
更改manifest.json以使用背景页面
您应该将manifest.json更改为xframeoptions.js的
content_scripts
键,而不是使用以下内容将其作为background
脚本运行:扩展分为后台脚本和内容脚本
如果您需要在内容脚本中调用API的信息,则需要使用message passing to communicate between the content script and your background script . 但是,通常可以将完整逻辑移动到在后台上下文中运行的脚本(后台脚本,弹出脚本,选项页脚本等) . 确切地说,将需要什么取决于您希望用脚本完成的任务 .
在后台上下文中可用的所有特权API之间的功能分离以及对内容脚本中可用的网页内容的访问(对特权API的访问非常有限),以及它们之间的异步消息传递,是extensions are architected的基础 . 您需要围绕此架构设计扩展 .
可能由此问题引起的一些错误
此问题可能导致许多可能的错误 . 以下是可能错误的不完整列表: