javascript - 使用 Firefox native 消息进行异步 webRequest.onBeforeRequest URL 检查

标签 javascript firefox-addon-webextensions chrome-native-messaging

我正在尝试使用 Firefox native 消息创建 URL 检查器。问题是,当 native 应用程序发送判决时,onBeforeRequest 监听器已经释放了请求,因此不会发生重定向。 您能否帮助我的分机等待回复最多 2 秒,如果答案为“0”,则重定向请求?

var port = browser.runtime.connectNative("ping_pong");

function inspectURL(requestDetails) {
    console.log("Loading: <" + requestDetails.url + ">");
    port.postMessage(requestDetails.url);
    console.log("Posting complete <" + requestDetails.url + ">");
}

port.onMessage.addListener((response) = > {
    console.log("Received: <" + response + ">");
    if (response == "1")
    {
        console.log("Good url!!!");
    }
    else
    {
        console.log("BAD url - redirecting!!!");
        return {
        redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
        };
    }
});

browser.webRequest.onBeforeRequest.addListener(
    inspectURL,
    { urls: ["<all_urls>"] },
    ["blocking"]
);

最佳答案

火狐浏览器

从 Firefox 52 开始,Firefox 支持异步 webRequest 阻止/修改监听器。为此(MDN:webRequest: Modifying requests(以及多个其他页面)):

From Firefox 52 onwards, instead of returning BlockingResponse, the listener can return a Promise which is resolved with a BlockingResponse. This enables the listener to process the request asynchronously.

因此,在您的 wrbRequest.onBeforeRequest 监听器中,您返回一个 Promise,并使用 BlockingResponse 解析该 Promise。

您需要存储您从端口请求信息的请求列表。来自您的端口响应需要唯一地标识它所响应的请求。请记住,这都是异步的,因此您可以同时处理多个请求。您必须适本地跟踪这些并且仅解决适当的 Promise。假设您的端口 的响应不会快速变化,您应该存储已检查的 URL 列表(好的和坏的),以便您可以立即响应已检查的 URL。

Chrome

您想要的东西在 Chrome 中是不可能实现的。您需要以其他方式解决您的问题。

关于javascript - 使用 Firefox native 消息进行异步 webRequest.onBeforeRequest URL 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310381/

相关文章:

npapi - Edge 中 Chrome native 消息传递的等效项

javascript - Chrome Native Messaging API chrome.runtime.connectNative 不是函数

c++ - 如何在 Chrome Native Messaging Extension 的 native 应用程序中使用 native 主机消息

javascript - 关闭 2 个内联元素之间的间隙

javascript - 如何修复 TypeError : browser. storage is undefined in chrome/firefox web extension?

javascript - Xhttp 未在 Firefox 附加组件中触发请求

javascript - 如何获取网络扩展图标来调用javascript

javascript - 提交表单到其他页面

javascript - 在 Chart.js 中使用准备好的数据集

Javascript foreach循环多次调用ajax