假设来自服务器的HTML文件包含以下标题:
Content-Type: application/octet-stream
Content-Disposition: attachment;
我想更改网络扩展程序中的标题(以便将HTML文件显示为常规网页):
Content-Type: text/html; charset=utf-8
(Removed Content-Disposition)
在Google Chrome中,网络扩展程序成功更改标题,HTML文件显示为普通网页。在Firefox(48)中,虽然标题已更改,但系统会提示我下载HTML文件。我做错了什么或这是一个已知的错误?
请求示例: localhost:8000 / test.html
以下代码。
网络扩展程序 - manifest.json :
{
"description": "Change content type",
"manifest_version": 2,
"name": "change-content-type",
"version": "1.0",
"permissions": [
"webRequest", "webRequestBlocking", "http://localhost/*"
],
"background": {
"scripts": ["background.js"]
}
}
网络扩展程序 - Background.js 如下所示:
function setHeader(headers, name, value) {
for (var header of headers) {
if (header.name.toLowerCase() == name.toLowerCase()) {
header.value = value;
return;
}
}
headers.push({ name : name, value : value });
}
function removeHeader(headers, name) {
for (var i = 0; i < headers.length; i++) {
if (headers[i].name.toLowerCase() == name.toLowerCase()) {
headers.splice(i, 1);
return;
}
}
}
function changeResponseHeaders(details) {
removeHeader(details.responseHeaders, "Content-Disposition");
setHeader(details.responseHeaders, "Content-Type", "text/html; charset=utf-8");
return {
responseHeaders: details.responseHeaders
};
}
chrome.webRequest.onHeadersReceived.addListener(
changeResponseHeaders, {
urls: ["http://localhost/*"],
types: ["main_frame", "sub_frame"]
}, ["blocking", "responseHeaders"]
)
微小的网络服务器(作为示例):
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def guess_type(self, path):
return 'application/octet-stream';
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Content-Disposition", "attachment;")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
示例HTML文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div>Test</div>
</body>
</html>