简体   繁体   中英

chrome.webRequest.onBeforeRedirect not stopping redirect?

I am developing a chrome extension, and in part of the extension I need to detect redirection and ask the user whether he/she wishes to proceed. I tried doing this using chrome's webRequest API, but it doesn't seem to work properly, even though I'm sure my syntax is right. Here is the relevant code:

chrome.webRequest.onBeforeRedirect.addListener(function (details) {
    if(details.frameId == 0){
        if (confirm("This link is a redirect. Do you want to continue?")){
            /* do nothing and let them redirect */
        }
        else {
            /* stop the redirect from happening */
            return {cancel: true};
        }
    }
}, {urls: ["<all_urls>"], types: ["main_frame"]}, ["blocking"]);

Why isn't the method blocking properly?

According to official guide , you're not allowed to cancel the redirect

onBeforeRedirect

Fires when a redirect is about to be executed. A redirection can be triggered by an HTTP response code or by an extension. This event is informational and handled asynchronously. It does not allow you to modify or cancel the request.

Haibara is perfectly correct in that onBeforeRedirect is purely informational, but let me add to that.

onBeforeRequest and onBeforeSendHeaders are the only events that can - ie cancelling is only possible before the request is actually made. It's a question of defining "cancel", since the request is already out.


Note that you can use onHeadersReceived for your purpose - headers provided in that event are the ones used to redirect the request, and you can override it by redirecting (which is allowed at that point) to your own extension page.


However, I must also say that you may be chasing the wrong suspect here. As far as I understand webRequest , this will only catch HTTP 3** redirects ; any other redirect method, such as changing window.location , will mean that this particular network request succeeds, and then generates a subsequent navigation, which is transparent to webRequest .

All the while the HTTP 3** redirects are most often used for benign purposes of rewriting http to https or modifying the URL to a canonical one.

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