How to cancel webRequest silently in chrome extension

与世无争的帅哥 提交于 2019-12-18 04:48:14

问题


I'm re-posting my question from Chromium-extensions google group here.

In my extension, I want to cancel some webRequests based on url pattern. My problem is that, if I return {cancel:true} in the onBeforeRequest event listener, the browser would redirect to a page telling me that the request is blocked by some extension. But I just want to cancel the request silently(as nothing happened).

I have also tried to return {redirectUrl:""} in the onBeforeRequest event listener, the console would log an error saying that "" was not a valid URL, and a bar appeared at the bottom of the browser, saying "Waiting for extension". To dismiss that bar, I then run content script "window.stop()" in that web page. That works sometimes, but not always. So I wonder if someone has any better solution. Thanks!!


回答1:


You should use "javascript:" url instead :

{
    redirectUrl:"javascript:"
}



回答2:


Redirect to a page which replies with HTTP status code 204, e.g. https://robwu.nl/204 This is my website, and I do not log any traffic to this URL.

The specification demands the following behavior for a response with HTTP status 204:

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

Here is a simple example, an extension that silently blocks all requests to YouTube:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
    var scheme = /^https/.test(details.url) ? 'https' : 'http';
    return { redirectUrl: scheme + '://robwu.nl/204' };
}, {
    urls: ['*://www.youtube.com/*'] // Example: Block all requests to YouTube
}, ['blocking']);

This example redirects to http://robwu.nl/204 or https://robwu.nl/204 depending on the requests's scheme, to avoid mixed content warnings.

To get this example to work, you need to declare the webRequest, webRequestBlocking and host permissions for the site in the manifest file.




回答3:


return {redirectUrl: 'javascript:void(0)'};


来源:https://stackoverflow.com/questions/18684024/how-to-cancel-webrequest-silently-in-chrome-extension

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