简体   繁体   English

Google Chrome 扩展中的同步调用

[英]Synchronous call in Google Chrome extension

I'm working on Google Chrome extension, which has to block/redirect some outgoing requests.我正在开发 Google Chrome 扩展程序,它必须阻止/重定向一些传出请求。 For this purpose, I use chrome.webRequest.onBeforeRequest listener.为此,我使用chrome.webRequest.onBeforeRequest侦听器。 To decide, whether to block request or not, I need some information about the tab request is sent from.要决定是否阻止请求,我需要一些有关发送选项卡请求的信息。 I can get it using chrome.tabs.get(integer tabId, function callback) , but callback is asynchronous, which means it may be called after the value is returned from onBeforeRequest listener.我可以使用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"]);

Is there a way to synchronize the call?有没有办法同步通话? Or maybe some other option.或者也许是其他一些选择。

Another answer on Stack Overflow recommends keeping track of the tabs outside of your listener function, which avoids this problem entirely. Stack Overflow 上的另一个答案建议跟踪监听器函数之外的选项卡,这完全避免了这个问题。

Example code:示例代码:

/* 
 * --------------------------------------------------
 * 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"]);
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

官方文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM