Google chrome 选项卡激活后的Chrome扩展回调

Google chrome 选项卡激活后的Chrome扩展回调,google-chrome,google-chrome-extension,Google Chrome,Google Chrome Extension,我有一个扩展,我想在不同的时间集中标签几秒钟 我可以更改选项卡,但是,我希望在选项卡聚焦时传入回调函数 我尝试将一个函数传递到sendMessage,但它似乎立即执行(如下所示)。一旦选项卡被聚焦,如何传入回调函数以在内容脚本中执行 content_script.js chrome.runtime.sendMessage("Do something", function(resp) { console.log(resp) }) background.js chrome.runtime.

我有一个扩展,我想在不同的时间集中标签几秒钟

我可以更改选项卡,但是,我希望在选项卡聚焦时传入回调函数

我尝试将一个函数传递到
sendMessage
,但它似乎立即执行(如下所示)。一旦选项卡被聚焦,如何传入回调函数以在内容脚本中执行

content_script.js

chrome.runtime.sendMessage("Do something", function(resp) {
    console.log(resp)
})
background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  chrome.windows.update(sender.tab.windowId, {"focused": true}, function(window){ });
  chrome.tabs.update(sender.tab.id, {"active": true}, function(tab){
    // callback function
  });
});
要保持响应通道打开,请从chrome API回调调用
sendResponse
。注意,ChromeAPI回调总是在主函数完成后运行

chrome.runtime.onMessage.addListener(函数(请求、发送方、发送响应){
让callbackCounter=2;
更新(sender.tab.id,{active:true},函数(tab){
//此回调在父函数完成后运行
如果(--callbackCounter==0){
sendResponse({foo:'bar'});
}
});
chrome.windows.update(sender.tab.windowId,{focused:true},函数(window){
//此回调在父函数完成后运行
如果(--callbackCounter==0){
sendResponse({foo:'bar'});
}
});
//保持响应通道畅通
返回true;
});
在现代浏览器中,这通常通过Promise API解决。
您可以通过加载将其与ChromeAPI一起使用

browser.runtime.onMessage.addListener((请求,发送方)=>{
回报你的承诺([
browser.tabs.update(sender.tab.id,{active:true}),
browser.windows.update(sender.tab.windowId,{focused:true}),
]).然后(()=>{
// .........
返回{foo:'bar'};
});
});
polyfill还允许您使用等待/异步语法:

browser.runtime.onMessage.addListener(异步(请求,发送方)=>{
等待承诺([
browser.tabs.update(sender.tab.id,{active:true}),
browser.windows.update(sender.tab.windowId,{focused:true}),
]);
返回{foo:'bar'};
});