• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

通过chrome.runtime.sendMessage发送带有函数的对象

用户头像
it1352
帮助1

问题说明

我正在开发一个chrome扩展,我想用chrome.runtime.sendMessage发送一个对象(带有一些函数)。

I am developing a chrome extension where I want to send an object ( with some functions ) around with chrome.runtime.sendMessage.

现在做这样的事情

chrome.runtime.sendMessage({something: "Funny"}); 

工作正常。但是只要我想创建更复杂的东西,我的消息似乎就是一个空对象。

works just fine. But as soon as I want to create something more complex my message seems to be an empty object.

function FunnyFunction() {
    return 42;
}
var exampleObject = new Object();
exampleObject.FunnyFunction = FunnyFunction;

chrome.runtime.sendMessage({something: exampleObject });

现在在接收端,它成功注册了一条消息,并检测到它有一个键某事 。
但是exampleObject总是空的。内部没有任何功能。

Now on the receiving end it successfully registeres a message and also detects that it has a key "something". But exampleObject is always empty. No functions inside.

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log("got message: ");
        console.log(request);
        if ('something' in request) {
            exampleObject = request.exampleObject;
            console.log(exampleObject);
        }
    }
);

请求始终是对象

Object {something: Object}

但是'某事'背后的对象,应该是exampleObject - 我之前用2个函数定义的对象 - 总是空的。

But the object behind 'something', which should be exampleObject - the object I definied earlier with 2 functions - is always just empty.

Object {}

当我尝试做exampleObject.FunnyFunction();它显然崩溃了,因为它没有这样的成员。

When I try to do exampleObject.FunnyFunction(); it obviously crashes, because it has no such member.

我在这里做错了什么?

正确答案

#1

您不能通过Message Passing API传递函数,因为它使用序列化的JSON作为数据交换格式,它不支持作为基本类型的函数。理想情况下,您可能已经在您需要的上下文中使用该功能(即背景/事件页面,弹出页面等),但是,如果您需要将功能从扩展的一部分传递到另一部分,您需要使用 JSON.stringify 将函数序列化为JSON字符串,并在另一端使用 JSON.parse 将JSON字符串反序列化回原始函数,然后您可以使用它。

You can't pass functions through the Message Passing API because it uses serialized JSON as the data interchange format, which doesn't support functions as a basic type. Ideally, you would already have the function available in the context upon which you need it (i.e. background/event page, popup page, etc.) but, in a case where you need to pass a function from one part of your extension to another, you would need to use JSON.stringify to serialize the function into a JSON string and, at the other end, use JSON.parse to deserialize the JSON string back into the original function, upon which you can then utilize it.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhchaakh
系列文章
更多 icon
同类精品
更多 icon
继续加载