chrome.runtime.onMessage侦听器永远不会触发

时间:2019-04-07 19:34:16

标签: javascript google-chrome-extension

我正在尝试为Chrome中的每个标签设置特定的徽章文本。

尽管没有chrome.runtime.onMessage事件处理程序被触发,但我一直遵循这个答案https://stackoverflow.com/a/32168534/8126260

// tab specific badges https://stackoverflow.com/questions/32168449/how-can-i-get-different-badge-value-for-every-tab-on-chrome
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log('runtime message');
  if (message.badgeText) {
    console.log('runtime message with badge text');
      chrome.tabs.get(sender.tab.id, function(tab) {
          if (chrome.runtime.lastError) {
              return; // the prerendered tab has been nuked, happens in omnibox search
          }
          if (tab.index >= 0) { // tab is visible
              chrome.browserAction.setBadgeText({tabId:tab.id, text:message.badgeText});
              console.log('set message');
          } else { // prerendered tab, invisible yet, happens quite rarely
              var tabId = sender.tab.id, text = message.badgeText;
              chrome.webNavigation.onCommitted.addListener(function update(details) {
                  if (details.tabId == tabId) {
                      chrome.browserAction.setBadgeText({tabId: tabId, text: text});
                      chrome.webNavigation.onCommitted.removeListener(update);
                  }
              });
          }
      });
  }
});

// block outgoing requests for help widgets
chrome.webRequest.onBeforeRequest.addListener(
              function(details) {
                //send message

                console.log('send message');
                chrome.runtime.sendMessage({badgeText: "HELP"});

                  if (isDisabled) {
                    return { cancel: false } // this should return from the function (details) level
                  } else {
                    return { cancel: true }
                  }
              },
              {urls: [
                "a bunch of urls irrelevant to this question"
              ]},
              ["blocking"]);

(整个源代码位于https://github.com/bcye/Hello-Goodbye上)

查看我的后台脚本的控制台,出现发送消息,这意味着chrome.runtime.sendMessage({badgeText: "HELP"});应该已经执行。

尽管onMessage侦听器中的console.log语句均未执行。

1 个答案:

答案 0 :(得分:0)

解决了该问题,因为@wOxxOm表示这是不可能的。

尽管webRequest在详细信息字典中传递了tabId。 这可以用来复制它。