BrowserExtension webRequest.onBeforeRequest return promise

心已入冬 提交于 2019-12-20 05:19:09

问题


I have the following in a Chrome and FireFox extension:

function webListener(requestDetails) {
    var asyncCancel = new Promise((resolve, reject) => {
        resolve({ cancel : true });
    });
    return asyncCancel;
}

chrome.webRequest.onBeforeRequest.addListener(
    webListener, {
        urls: ["<all_urls>"],
        types: ["script"]
    }, ["blocking", "requestBody"]
);

The problem is that it doesn't cancel the request. I read Chrome docs and Firefox docs and for Firefox it says it's based on Chrome's API and can return a promise to handle the request asynchronously..

However, unless I make it synchronous, it fails to cancel (IE: If I return just {cancel : true} instead of the promise, it works).

Am I doing something wrong or does Chrome and Firefox only support synchronous request handling here?


回答1:


The Chrome documentation reads to me as though you must use a synchronous, blocking response to cancel a request, and that has been my experience also.

Emphasis mine :

If the optional opt_extraInfoSpec array contains the string 'blocking' (only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns. In this case, the callback can return a webRequest.BlockingResponse that determines the further life cycle of the request. Depending on the context, this response allows cancelling or redirecting a request (onBeforeRequest), cancelling a request or modifying headers (onBeforeSendHeaders, onHeadersReceived), and cancelling a request or providing authentication credentials (onAuthRequired).

My reading is that you can only influence the request lifetime(like cancelling it) if your event handler is synchronous.

Furthermore, the docs also don't mention anything about supporting a Promise instead of a BlockingResponse directly, so it seems that that is Firefox-specific functionality.



来源:https://stackoverflow.com/questions/47910732/browserextension-webrequest-onbeforerequest-return-promise

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