【问题标题】:chrome extension message passsing: sendResponse is not a functionchrome 扩展消息传递:sendResponse 不是函数
【发布时间】:2018-06-18 08:26:16
【问题描述】:

在我的 Chrome 扩展程序中,我试图在扩展程序 chrome-extension://myExtensionId/path/to/web/page.html 的内部网页和内容脚本之间交换数据。

所以,为了使这些数据在不同的内容脚本中持久存在,我试图将其保存为 全局变量 在扩展程序的后台!我使用消息传递来做到这一点。

我的问题是:

当我尝试从后台发回响应时,我收到此错误:

事件处理程序中的错误(未知):TypeError:sendResponse 不是 功能

我关注了documentation's examples,这是我的尝试:

scriptOfTheInternalPage.js

var message = {
    'order': 'setData',
    'varName': 'myArray',
    'data': myArray
};
extPort.postMessage(message, function (response) {
    console.log('response:\n', JSON.stringify(response));
});

background.js

var globals = {
    'myArray': [],
    ...
};
chrome.runtime.onConnect.addListener(function (port) {
    port.onMessage.addListener(
            function (message, sender, sendResponse) {
                console.log(
                        'the port received this message:\n', JSON.stringify(message), '\n',
                        (sender.tab) ? ' from tab #' + sender.tab.id : ' from the extension!'
                        );
                if (message.order === 'setData') {
                    globals[message.varName] = message.data;
                    sendResponse({'response': 'data saved!'}); //<=====
                }
                return true; //<=== tried to return true here as well;
            });
});

这个错误是否意味着我应该在onMessage 事件监听器之外创建一个全新的函数?

我很困惑!我错过了什么?

【问题讨论】:

  • all port.onMessage.addListener 的示例类似于 port.onMessage.addListener(function(msg) { - 没有一个将 function (message, sender, sendResponse) { 作为回调“模式” - 您正在使用回调模式作为为chrome.runtime.onMessageExternal.addListener(chrome.runtime.onMessage.addListener( 描述

标签: javascript google-chrome-extension


【解决方案1】:

端口的onMessage 事件侦听器与runtime.onMessage 的签名不同。你没有得到sendersendResponse 参数,只有消息。返回true 也无效。

要回复消息,您需要使用端口本身。这是covered by examples

port.onMessage.addListener(function(msg) {
  if (msg.joke == "Knock knock")
    port.postMessage({question: "Who's there?"});
}

因此,您确实需要双方都有一个onMessage 侦听器,并且如果可以进行多个请求,还需要一些方法来跟踪请求(唯一 ID?)。

【讨论】:

  • 感谢您的澄清!这令人困惑!
猜你喜欢
  • 2011-03-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多