Chrome扩展WebRequest过滤tabId不工作

Chrome extensions WebRequest filtering by tabId not working?

本文关键字:工作 tabId 过滤 扩展 WebRequest Chrome      更新时间:2023-09-26

我正在重构一个现有的chrome扩展,我有一个调用chrome.webRequest.onBeforeSendHeaders,应该根据当前选择的选项卡进行过滤。

我在这里使用文档,关于过滤,它声明:

webRequest。RequestFilter过滤器允许限制请求在不同维度中触发哪些事件:

URLs URL模式,如*://www.google.com/foo*bar。类型的请求类型,如main_frame(为顶层加载的文档), sub_frame(为嵌入帧加载的文档),还有图片(网站上的图片)。看到webRequest.RequestFilter。选项卡ID标签的标识符。Window ID窗口的标识符。

由此,我的理解是,如果我将tabid定义为侦听器的一部分,我应该根据选项卡ID过滤所有请求(因此,只捕获来自该特定选项卡的请求头)。

问题是这不会发生。当我采用tabid:xx过滤器时,我一直捕捉来自我打开的各种选项卡的所有请求。

我错过了什么?

下面是我的示例代码从后台脚本background.html:
var currentTabId = -1;
chrome.tabs.getSelected(null, function(tab){ 
    currentTabId = tab.id;
    console.log("tab id in getselected "+currentTabId);
});
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(req){
        console.log("-> Request Headers received for "+req.url);
        console.log('onBeforeSendHeaders tab id: '+currentTabId)
        console.log('onBeforeSendHeaders: '+JSON.stringify(req))
    }
, { urls:["http://*/*", "https://*/*"], tabId: currentTabId }, ['requestHeaders','blocking']);

currentTabId是例如1666,而对象req中的tabId是另一个,这可能来自我打开的任何选项卡,我正在使用(它没有过滤掉1666)。

您的示例代码执行顺序错误;chrome.tabs.getSelected是异步的

var currentTabId = -1;
chrome.tabs.getSelected(null, function(tab){
    currentTabId = tab.id;
    // Here, currentTabId is defined properly
    console.log("tab id in getselected "+currentTabId);
});
// Here, it is still -1

您需要将addListener调用移动到getSelected回调中:

chrome.tabs.getSelected(null, function(tab){ 
    currentTabId = tab.id;
    console.log("tab id in getselected "+currentTabId);
    chrome.webRequest.onBeforeSendHeaders.addListener(/*...*/);
});