chrome.runtime.onMessage.addListener 未在创建的选项卡中注册
chrome.runtime.onMessage.addListener not registering within created tab
当我创建一个新标签时,以下脚本是从我的 background.js 注入的(新标签加载一个站点,即 Google.com)。
$(function(){
//this fires when tab is created and script injected
chrome.runtime.sendMessage({title: window.document.title}, function(){});
//this fires when clicking on element in created tab
document.getElementById("Username").addEventListener("click", function(){
chrome.runtime.sendMessage({someMessageFromLiveSite: 'Clicked in live site!'});
});
chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
//this never fires
chrome.runtime.sendMessage({title: 'This is the created tab responding to a msg'}, function(){});
//code continues...
如上所述,chrome.runtime.sendMessage
似乎工作正常,香草 JS 事件侦听器也是如此,但 chrome.runtime.onMessage
侦听器似乎 added/is 未响应发送的消息来自扩展的其他部分(背景或其他创建的页面)。
感谢 Xan's answer here,我意识到我正试图使用 chrome.runtime.sendMessage
从后台向我创建的所有选项卡广播一条消息,但如前所述,这不会广播,因此 [=需要 11=] 才能让听众响应我创建的内容选项卡。
虽然标题对于我遇到的问题在技术上不准确,但在我看来是正确的症状,所以这个答案可能对其他人有帮助。
当我创建一个新标签时,以下脚本是从我的 background.js 注入的(新标签加载一个站点,即 Google.com)。
$(function(){
//this fires when tab is created and script injected
chrome.runtime.sendMessage({title: window.document.title}, function(){});
//this fires when clicking on element in created tab
document.getElementById("Username").addEventListener("click", function(){
chrome.runtime.sendMessage({someMessageFromLiveSite: 'Clicked in live site!'});
});
chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
//this never fires
chrome.runtime.sendMessage({title: 'This is the created tab responding to a msg'}, function(){});
//code continues...
如上所述,chrome.runtime.sendMessage
似乎工作正常,香草 JS 事件侦听器也是如此,但 chrome.runtime.onMessage
侦听器似乎 added/is 未响应发送的消息来自扩展的其他部分(背景或其他创建的页面)。
感谢 Xan's answer here,我意识到我正试图使用 chrome.runtime.sendMessage
从后台向我创建的所有选项卡广播一条消息,但如前所述,这不会广播,因此 [=需要 11=] 才能让听众响应我创建的内容选项卡。
虽然标题对于我遇到的问题在技术上不准确,但在我看来是正确的症状,所以这个答案可能对其他人有帮助。