Google chrome extension Chrome扩展:从popup.js到content.js的消息

Google chrome extension Chrome扩展:从popup.js到content.js的消息,google-chrome-extension,Google Chrome Extension,在我的Chrome扩展中,我试图将一条消息从popup.js发送到content.js。这需要根据弹出窗口中的事件发生,因此不能在内容或背景消息中触发 我使用下面的代码只是为了测试消息是否被传递 在popup.js中: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, f

在我的Chrome扩展中,我试图将一条消息从
popup.js
发送到
content.js
。这需要根据弹出窗口中的事件发生,因此不能在内容或背景消息中触发

我使用下面的代码只是为了测试消息是否被传递

popup.js中

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
             alert(response.farewell);
          });
        });
content.js
中:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        alert(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
  });
;
问题是,只有当我打开一个新选项卡时,消息才会被传递(提醒),而不是当我处于活动选项卡时

用户可以在弹出窗口中选择一个设置,然后使
content.js
通过不同的数据发送。因此,我应该能够在用户单击特定按钮时发送消息


有人能帮忙吗?因为在关于这个问题的所有其他问题中,我只看到了谷歌页面上关于消息传递的链接。这段代码就是从这里开始的。

您可以尝试不使用
alert()
?它冻结异步流,并可能导致弹出窗口关闭。在主题上使用
console.log()
并查看相应的控制台(页面的控制台和上下文菜单中的“检查弹出窗口”),这可能是这个问题:使用
console.log仍然不起作用。我已经看过了你发布的链接,但是提到注入脚本我有点困惑,这就是我正在做的吗?因为看起来不一样。还有其他解决这个问题的方法吗?@ALR你能在哪里解决你的问题?