【问题标题】:Block downloading by Content-Type via Chrome Extension通过 Chrome 扩展按 Content-Type 阻止下载
【发布时间】:2014-01-06 22:49:11
【问题描述】:

我正在开发一个扩展,用于阻止按文件的 Content-Type 下载。这是处理标头接收的后台脚本的一部分:

chrome.webRequest.onHeadersReceived.addListener(function(details) {
    var headers = details.responseHeaders;

    for(var i = 0, l = headers.length; i < l; ++i) {
        if(headers[i].name == "Content-Type" && headers[i].value == "<some_type>") {
            return {cancel: true};
        }
    }
}, {urls: ["<all_urls>"]}, ["responseHeaders", "blocking"]);

我得到带有错误消息的页面:

所以我需要一些解决方案来让用户保持在前一页上,而无需重新加载以显示此错误页面,或者在显示此服务页面后以某种方式返回。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension http-headers


    【解决方案1】:

    如果您希望防止在基于内容类型的 (i) 框架中导航离开,那么您就不走运了 - 此时无法阻止页面卸载。

    如果您想阻止顶级框架导航离开,那么就有希望了。您可以将页面重定向到回复 HTTP 状态代码 204 的资源。

    chrome.webRequest.onHeadersReceived.addListener(function(details) {
        // ... your code that checks whether the request should be blocked ...
    
        if (details.frameId === 0) { // Top frame, yay!
            var scheme = /^https/.test(details.url) ? "https" : "http";
            chrome.tabs.update(details.tabId, {
                url: scheme + "://robwu.nl/204"
            });
            return;
        }
        return {cancel: true};
    }, {
        urls: ["<all_urls>"],
        types: ["main_frame", "sub_frame"]
    }, ["responseHeaders", "blocking"]);
    

    issue 280464 解决后,也可以使用前面的方法来防止子帧中的卸载。

    https://robwu.nl/204 是我网站的一部分。不记录对该 URL 的访问。对此条目的响应将始终为“204 No Content”。

    【讨论】:

    • @RobW 给定的解决方案不会阻止下载,仅使用“return”会导致下载开始。
    • @adnankamili 要解决该问题,您可以将 content-type 标头更改为不可下载的文本/纯文本,添加 content-type-options: no-sniff(以禁用 MIME 嗅探)。虽然老实说,这个答案是一个真正的黑客。如果您的意图是取消请求,那么您真的应该使用{cancel: true}
    • @RobW 仍然没有运气,我不能使用 {cancel: true} 因为它会导致该阻止页面出现。我尝试了 return {redirectUrl: ""};,这阻止了 weblock 页面,但函数没有返回并且扩展继续等待。你能推荐一些其他的技巧吗,因为我非常需要它。
    • redirectUrl 尚不支持(尽管我正在开发一个实现,请参阅crbug.com/280464#4 了解详细信息)。此外,当您提供请求时,Chromium 中的一个错误会阻止请求完成(请参阅crbug.com/348417,已在 Chrome 35 中修复)。我之前建议的 hack(修改标题以使用 Content-Type: text/plainX-Content-Options: nosniff)应该可以工作。如果没有,那么您需要显示您的代码。
    • @RobW 我已经用代码stackoverflow.com/questions/22593735/… 开启了一个新问题,还尝试了涉及更改响应行 302 Moved Temporarily but it didn't work
    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    相关资源
    最近更新 更多