Since this question Block downloading by Content-Type via Chrome Extension didn't work for me, I am opening a new question. I use the following code to block download based on content-type header:
chrome.webRequest.onHeadersReceived.addListener(function(details) {
preventDownload = false;
details.responseHeaders.push({name:"X-Content-Options",value: "no-sniff"}); // Hack 1
details.statusLine = "HTTP/1.1 302 Moved Temporarily"; // Hack 2
for (var i = 0; i < details.responseHeaders.length; ++i)
{
if (details.responseHeaders[i].name == 'Content-Type')
{
var contentType = details.responseHeaders[i].value;
if (contentType.indexOf("application/xyz")!=-1)
{
preventDownload = true;
details.responseHeaders[i].value = 'text/plain'; //Hack 3
}
else
{
return {responseHeaders: details.responseHeaders};
}
}
}
if(preventDownload)
{
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}; should be used but it displays block page
}
return {cancel: true};
}
return {responseHeaders: details.responseHeaders};
}, {urls: ["<all_urls>"],types: ["main_frame", "sub_frame"]}, ['blocking', 'responseHeaders']);
I succeed in preventing the download, but an error Web block page appears. I need to keep user on previous page without reloading to displaying this error page OR somehow move back from this service page after it displayed.
I have used a hack in above code but it does not block the download.