gpt4 book ai didi

JavaScript - 等待异步函数完成

转载 作者:行者123 更新时间:2023-12-03 01:37:08 25 4
gpt4 key购买 nike

在我的 Chrome 扩展程序中,我检查特定域下的每个网络请求。如果网址与特定条件匹配,并且存在与另一个网址匹配的现有打开选项卡,我想返回{cancel: true},这意味着请求是已被阻止。

所以我的代码是这样工作的:如果请求的 URL 符合我的条件,则检查所有打开的选项卡。如果打开的选项卡之一符合我的(第二个)条件,我想从初始(外部)函数返回 {cancel: true}

问题: 在检查所有选项卡之前(= 在执行所有 forEach 循环之前),外部函数的 return 会触发),因此它总是返回 {cancel: false}

[我知道有很多与此相关的问题,主要解决方案之一包括回调函数,但具体到我的情况,我还没有成功地实现这项工作。]

代码:

function onBeforeRequestHandler (details) {
var cancel = false;
var url = details.url;
// condition 1
if (url.indexOf("condition_1") > -1){

// check all open windows/tabs
chrome.windows.getAll({populate:true}, function(windows){
windows.forEach(function(single_window){
single_window.tabs.forEach(function(tab){
// condition 2
if (tab.url.indexOf("condition_2") > -1){
cancel = true;
// this is less important - updating the tab works
chrome.tabs.update(tab.id, {url: url});
}
});
});
});
// always getting cancel = false here because it fires too quickly
return {cancel: cancel};
}
else
return {cancel: false};
}

chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestHandler, {urls: ["some_domain"]}, ["blocking"]);

最佳答案

目前,您无法在 Google Chrome 中取消基于异步功能的请求。

在Firefox中,它已经支持Promise的异步功能,您可以像下面的代码一样实现。

function onBeforeRequestHandler (details) {
var cancel = false;
var url = details.url;
// condition 1
if (url.indexOf("condition_1") > -1){
// check all open windows/tabs
// return Promise which will be resolved after populate windows/tabs
return browser.windows.getAll({populate:true})
.then(function(windows) {
windows.forEach(function(single_window) {
single_window.tabs.forEach(function(tab) {
// condition 2
if (tab.url.indexOf("condition_2") > -1) {
// this is less important - updating the tab works
browser.tabs.update(tab.id, {url: url});
return { cancel: true }
}
});
});
})
}
else
return {cancel: false};
}

历史/引用文献

根据MDN中的webRequest.onBeforeRequest

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. https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/webRequest/onBeforeRequest

已经在 Chrome 上报告了像 Firefox 一样的功能请求,但此票证尚未关闭。 https://bugs.chromium.org/p/chromium/issues/detail?id=625860

关于JavaScript - 等待异步函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51016605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com