【问题标题】:Chrome extensions WebRequest filtering by tabId not working?按 tabId 过滤的 Chrome 扩展 WebRequest 不起作用?
【发布时间】:2014-07-02 18:27:26
【问题描述】:

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

我正在使用文档 here,关于过滤它指出:

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

URL 网址格式,例如 *://www.google.com/foo*bar。类型请求 诸如 main_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 上没有被过滤掉)。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension tabs


    【解决方案1】:

    您的示例代码执行顺序错误; 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(/*...*/);
    });
    

    【讨论】:

    • 感谢您的回答。所以我猜 -1 作为 tabId 过滤器值只是捕获所有标题事件。
    • 此外,我知道我应该使用chrome.tabs.query({active:true})...这只是一个老例子。
    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2013-12-24
    • 2017-05-26
    • 2012-01-22
    • 2012-08-08
    相关资源
    最近更新 更多