我正在尝试使用 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 aBlockingResponse
. 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/