首页 文章

选项卡处于活动状态后Chrome扩展回调

提问于
浏览
0

我有一个扩展,我想在不同时间关注标签几秒钟 .

我能够更改选项卡,但是,我想传递一个回调函数,以便在选项卡聚焦时 .

我已经尝试将函数传递给 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
  });
});

1 回答

  • 0

    Return true from onMessage listener保持响应通道打开,然后从chrome API回调中调用 sendResponse . 请注意,chrome API回调始终运行asynchronously,即在主函数完成后运行 .

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
      let callbackCounter = 2;
    
      chrome.tabs.update(sender.tab.id, {active: true}, function (tab) {
        // this callback runs after the parent function has finished
        if (--callbackCounter === 0) {
          sendResponse({foo: 'bar'});
        }
      });
    
      chrome.windows.update(sender.tab.windowId, {focused: true}, function (window) {
        // this callback runs after the parent function has finished
        if (--callbackCounter === 0) {
          sendResponse({foo: 'bar'});
        }
      });
    
      // keep the response channel open 
      return true;
    });
    

    在现代浏览器中,这通常使用Promise API来解决 .
    您可以通过加载Mozilla WebExtension polyfill将其与Chrome API一起使用 .

    browser.runtime.onMessage.addListener((request, sender) => {
      return Promise.all([
        browser.tabs.update(sender.tab.id, {active: true}),
        browser.windows.update(sender.tab.windowId, {focused: true}),
      ]).then(() => {
        // .........
        return {foo: 'bar'};
      });
    });
    

    polyfill还允许您使用await / async语法:

    browser.runtime.onMessage.addListener(async (request, sender) => {
      await Promise.all([
        browser.tabs.update(sender.tab.id, {active: true}),
        browser.windows.update(sender.tab.windowId, {focused: true}),
      ]);
      return {foo: 'bar'};
    });
    

相关问题