通过chrome.runtime.sendMessage发送带有函数的对象 [英] Sending Object with functions via chrome.runtime.sendMessage
问题描述
我正在开发一个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.
我在这里做错了什么?
推荐答案
您不能通过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.
这篇关于通过chrome.runtime.sendMessage发送带有函数的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!