【发布时间】:2019-08-28 23:33:33
【问题描述】:
我正在尝试为 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 语句都不会被执行。
【问题讨论】:
-
你是在后台脚本中向监听器发送消息吗?那行不通,目标应该是不同的页面。在同一页面中,您可以使用标准 js 方法,例如直接函数调用或自定义事件订阅者/发射器。
-
@wOxxOm 是的,我从 background.js 文件中发送它们。虽然我怎么能得到标签 ID,但由于直接调用函数,我不会得到发件人对象。
标签: javascript google-chrome-extension