javascript - BrowserExtension webRequest.onBeforeRequest 返回 promise

标签 javascript google-chrome-extension firefox-addon-webextensions

我在 Chrome 和 FireFox 扩展中有以下内容:

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"]
);

问题是它不会取消请求。我阅读了 Chrome 文档和 Firefox 文档,对于 Firefox,它说它基于 Chrome 的 API,并且可以返回异步处理请求的 promise 。

但是,除非我让它同步,否则它无法取消(IE:如果我只返回 {cancel : true} 而不是 promise,它会起作用)。

是我做错了什么还是 Chrome 和 Firefox 只支持这里的同步请求处理?

最佳答案

Chrome documentation对我来说,就好像您必须使用同步的阻塞响应来取消请求一样,这也是我的经验。

强调我的:

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

我的理解是,如果您的事件处理程序是同步的,您只能影响请求的生命周期(比如取消它)。

此外,文档也没有提及直接支持 Promise 而不是 BlockingResponse,因此这似乎是 Firefox 特定的功能。

关于javascript - BrowserExtension webRequest.onBeforeRequest 返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47910732/

相关文章:

用于字符串参数的 Javascript *and* 运算符

javascript - 基本的 jquery 延迟使用与 ajax

javascript - 检测在我的 Chrome 扩展之外生成的 DOM 更改

testing - 如何测试 Chrome Extension/Firefox WebExtension 代码?

javascript - 在 Firefox Web Extension 中使用 chrome.runtime.sendMessage 不会产生响应

javascript - 基于 AJAX 的 Web 应用程序

javascript - 无法读取未定义的属性 'username' - 在 Node.js 中通过电子邮件发送表单数据

javascript - 在两个内容脚本之间传递消息(通过后台)

javascript - 如何获取所有 chrome 内容设置?

javascript - 删除 cookie 数组 (WebExtensions)