我正在使用Google Chrome扩展程序,该扩展程序必须阻止/重定向某些传出请求。为此,我使用chrome.webRequest.onBeforeRequest
监听器。
要决定是否阻止请求,我需要一些有关标签请求的信息。我可以使用chrome.tabs.get(integer tabId, function callback)
来获取它,但回调是异步的,这意味着可以在从onBeforeRequest
侦听器返回值之后调用它。
chrome.webRequest.onBeforeRequest.addListener(function(details){
chrome.tabs.get(details.tabId, function(tab){
// get info from tab
});
// based on info from tab return redirect or not
}), {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["blocking"]);
有没有办法同步通话?或许还有其他一些选择。
答案 0 :(得分:13)
Another answer on Stack Overflow建议跟踪侦听器功能的外部标签,这样可以完全避免此问题。
示例代码:
/*
* --------------------------------------------------
* Keep list of tabs outside of request callback
* --------------------------------------------------
*/
var tabs = {};
// Get all existing tabs
chrome.tabs.query({}, function(results) {
results.forEach(function(tab) {
tabs[tab.id] = tab;
});
});
// Create tab event listeners
function onUpdatedListener(tabId, changeInfo, tab) {
tabs[tab.id] = tab;
}
function onRemovedListener(tabId) {
delete tabs[tabId];
}
// Subscribe to tab events
chrome.tabs.onUpdated.addListener(onUpdatedListener);
chrome.tabs.onRemoved.addListener(onRemovedListener);
/*
* --------------------------------------------------
* Request callback
* --------------------------------------------------
*/
// Create request event listener
function onBeforeRequestListener(details) {
// *** Remember that tabId can be set to -1 ***
var tab = tabs[details.tabId];
// Respond to tab information
}
// Subscribe to request event
chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestListener, {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["blocking"]);
答案 1 :(得分:0)