Block downloading by Content-Type via Chrome Extension

旧时模样 提交于 2019-12-23 03:38:19

问题


I am developing an extension for blocking downloading by file's Content-Type. This is part of background script which handle headers receiving:

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

And I get page with error message:

So I need some solution to keep user on previous page without reloading to displaying this error page OR somehow move back from this service page after it displayed.


回答1:


If you wish to prevent navigating away in an (i)frame based on the content type, then you're out of luck - it is not possible to prevent a page from unloading at this point.

If you want to prevent the top-level frame from navigating away, then there's hope. You can redirect the page to a resource that replies with HTTP status code 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"]);

Once issue 280464 is solved, the previous method can also be used to prevent unloads in subframes.

https://robwu.nl/204 is part of my website. Access to this URL is not logged. The response to this entry will always be "204 No Content".



来源:https://stackoverflow.com/questions/20960788/block-downloading-by-content-type-via-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!