9

我正在开发 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"]);

有没有办法同步通话?或者也许其他一些选择。

4

2 回答 2

13

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"]);
于 2014-02-26T21:43:42.797 回答
0
chrome.runtime.onMessage.addListener((message, rawSender, sendResponse) => {

        // here, you can call sendResponse method in any where asynchronous.

        return true;    // 这是重点,it's important
    }
);

// it also fit chrome.webRequest.onBeforeRequest.addListener

官方文件

于 2020-04-22T13:17:56.813 回答