简体   繁体   中英

Block downloading by Content-Type via Chrome Extension

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.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM