您可以侦听请求并根据tabId
字段进行过滤。当然,您需要跟踪活动选项卡(每个窗口一个选项卡)。
例如:
使用chrome.tabs.onActivated监听每个窗口的活动选项卡中的更改并将其存储tabId
在本地变量中。
使用chrome.windows.onRemoved停止跟踪关闭窗口的选项卡。
为适合您目的的任何chrome.webRequest.*事件注册侦听器。例如,要在请求准备好发送后立即在其中一个活动选项卡中获得任何请求的通知,请为chrome.webRequest.onBeforeRequest注册一个侦听器。
下面是一个完全做到这一点的示例扩展的源代码。
清单.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": false,
"background": {
"persistent": true,
"scripts": ["background.js"]
},
"permissions": [
"webRequest",
"*://*/*"
]
}
背景.js:
/* Keep track of the active tab in each window */
var activeTabs = {};
chrome.tabs.onActivated.addListener(function(details) {
activeTabs[details.windowId] = details.tabId;
});
/* Clear the corresponding entry, whenever a window is closed */
chrome.windows.onRemoved.addListener(function(winId) {
delete(activeTabs[winId]);
});
/* Listen for web-requests and filter them */
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (details.tabId == -1) {
console.log("Skipping request from non-tabbed context...");
return;
}
var notInteresting = Object.keys(activeTabs).every(function(key) {
if (activeTabs[key] == details.tabId) {
/* We are interested in this request */
console.log("Check this out:", details);
return false;
} else {
return true;
}
});
if (notInteresting) {
/* We are not interested in this request */
console.log("Just ignore this one:", details);
}
}, { urls: ["<all_urls>"] });
/* Get the active tabs in all currently open windows */
chrome.tabs.query({ active: true }, function(tabs) {
tabs.forEach(function(tab) {
activeTabs[tab.windowId] = tab.id;
});
console.log("activeTabs = ", activeTabs);
});