通过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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhchaakh
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
复制文件夹/文件而不修改属性?
it1352 07-15