1

我正在开发一个扩展,用于按文件的内容类型阻止下载。这是后台脚本的一部分,该处理头接收:通过Chrome扩展按内容类型阻止下载

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"]); 

我也得到页面错误信息: message

所以我需要一些解决方案,以保持用户以前的页面上无需重新加载,以显示这个错误页面或者在显示之后以某种方式从该服务页面移回。

回答

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无内容”。

+0

Thx,它工作的很棒! – mmatviyiv

+0

@RobW给定的解决方案不能阻止下载,只使用“return”会导致下载开始。 –

+0

@adnankamili为了解决这个问题,你可以将'content-type'头部改为不可下载的文本/纯文本,添加'content-type-options:no-sniff'(以禁用MIME嗅探)。虽然老实说,这个答案是一个真正的黑客。如果你的意图是取消一个请求,那么你应该真的使用'{cancel:true}'。 –