如何改造Chrome URL Throttler扩展实现请求并行处理?
解决Chrome请求延迟扩展的并行处理问题
原扩展的核心问题在于同步阻塞的延迟逻辑:使用while循环实现的delay函数会卡死扩展主线程,导致所有匹配规则的请求必须串行等待,无法并行处理。以下是具体的修改方案:
修改后的background.js代码
// 替换同步阻塞的delay为异步Promise版本,不占用主线程 const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); let handler; chrome.storage.onChanged.addListener(function(changes, namespace) { if (changes.hasOwnProperty('requestThrottler')) { const throttlerConfig = changes.requestThrottler.newValue; if (handler) { chrome.webRequest.onBeforeRequest.removeListener(handler); handler = null; } const urls = throttlerConfig.urls.filter((u) => !u.error && u.url !== '').map((u) => u.url.trim()); if (throttlerConfig.enabled && urls.length > 0) { chrome.browserAction.setIcon({path: 'icon48-warning.png'}); // 改为async函数,实现独立的异步延迟逻辑 handler = async (info) => { console.log(`URL Throttler: Intercepted ${info.url}, going to wait ${throttlerConfig.delay} ms...`); await delay(throttlerConfig.delay); console.log(`URL Throttler: Done with ${info.url}`); }; console.log('Blocking urls', urls); chrome.webRequest.onBeforeRequest.addListener( handler, { urls: urls }, // 添加asyncBlocking参数,告知浏览器支持异步阻塞处理 ["blocking", "asyncBlocking"] ); } else { chrome.browserAction.setIcon({path: 'icon48.png'}); } } });
关键修改说明
异步延迟函数替换
原while循环是同步阻塞逻辑,会占用主线程导致所有请求串行等待。改为基于setTimeout的Promise版本后,每个请求的延迟逻辑独立执行,不会阻塞其他请求的处理流程。异步请求处理器
将handler改为async函数,内部通过await等待延迟完成,同时自动返回Promise。这让Chrome浏览器能够单独处理每个请求的延迟,实现并行等待。启用异步阻塞支持
在chrome.webRequest.onBeforeRequest.addListener的extraInfoSpec参数中添加"asyncBlocking"(Chrome 116+支持),告知浏览器当前处理器是异步的,需要等待Promise完成后再继续处理该请求,同时不影响其他请求的并行处理。
注意事项
popup.js无需修改,其仅负责配置存储,不影响请求处理逻辑。- 确保Chrome版本在116及以上,
asyncBlocking参数才会生效;若需兼容旧版本,可考虑通过取消原请求+延迟后重新发起请求的方式实现,但复杂度更高,不如异步阻塞方案简洁。
内容的提问来源于stack exchange,提问作者Коцур Роман
相关产品推荐
相关产品推荐

