【问题标题】:Chrome extension callback after tab is active选项卡处于活动状态后的 Chrome 扩展回调
【发布时间】:2019-05-10 18:09:54
【问题描述】:

我有一个扩展程序,我想在不同时间聚焦标签几秒钟。

我可以更改选项卡,但是,我想在选项卡获得焦点时传入一个回调函数。

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

【问题讨论】:

    标签: google-chrome google-chrome-extension


    【解决方案1】:

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

    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'};
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2018-04-08
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      相关资源
      最近更新 更多