【问题标题】:Chrome extension : error when sending message back from injected script to background scriptChrome 扩展:从注入脚本向后台脚本发送回消息时出错
【发布时间】:2013-06-19 12:41:26
【问题描述】:

我正在尝试使用 chrome 扩展。我的目标是从后台脚本向注入脚本发送消息,并让注入脚本返回结果。

代码如下:

background.js

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab){
    chrome.tabs.executeScript(tabId, {'file': "content.js"}, 
        function(){
            chrome.tabs.sendMessage(tabId, {msg: 'test'}, 
                function(response){
                    console.log(response);
                }
            );
            return true;
        }
    );
});

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        sendResponse('test message');
        return true;
    }
);

我收到错误消息

Could not send response: The chrome.runtime.onMessage listener must return true if you want to send a response after the listener returns 

当在content.js内部调用sendResponse

我已经从听者那里返回了 true.. 困惑吗?
我错过了什么明显的东西吗?

【问题讨论】:

  • 这似乎不是问题所在。我可以删除该行而不会产生任何影响。错误在 content.js 中。
  • 您是否尝试在您的onMessage 侦听器中删除return true
  • 不确定为什么会出现该错误,但这可能与您使用 OnUpdate 动态生成侦听器这一事实有关。您可能想尝试另一种方法:将内容脚本添加到清单文件中,以便在文档运行时为所有 URL 加载。然后让内容脚本在加载时向后台页面发送一条消息。然后后台和内容脚本就可以正常通信了。
  • @vivek.m:你猜到这个了吗?
  • @ExpertSystem 是的,请在下面查看我的答案。忘记更新了。

标签: javascript google-chrome-extension


【解决方案1】:

我认为我的问题已由

解决
chrome.tabs.sendMessage(tabId, {action: 'test'}, 

注意,我在上述问题中错误地使用了msg 而不是action

另外,我不使用第三个参数sendResponse来避免全双工通信 我只是将内容脚本中的另一条消息发布回后台页面。

从内容脚本,使用以下方式向后台页面发送消息:

function SendMessageToBackgroundPage(data)
{
    chrome.runtime.sendMessage({
        action: 'kungfu',
        source: 'panda'
    });
}

在后台页面中使用:

chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
            switch (request.action) {
                case 'kungfu': alert(request.source);
            }
        });

【讨论】:

  • 我相信你应该使用 chrome.runtime.sendMessage/onMessage 而不是 chrome.extension.sendMessage/onMessage。特别是在使用事件页面(而不是背景页面)时,因为 chrome.runtime 函数确保在响应/采取任何操作之前正确加载暂停的背景页面。
  • @ExpertSystem 看起来 google 已从 latest docs 中删除了对 extension.sendMessage 的引用。更新了我的答案。
猜你喜欢
  • 2013-06-27
  • 1970-01-01
  • 2019-04-16
  • 2014-11-27
  • 2021-10-14
  • 2014-02-04
  • 2014-07-16
  • 1970-01-01
  • 2014-11-23
相关资源
最近更新 更多