对象类型在消息传递中丢失 [英] Object type is lost in message passing
问题描述
我正在研究Chrome扩展程序,并遇到以下问题。
当某个事件发生时,我的后台页面使用 chrome.tabs.create
API创建一个新选项卡(页面),并发送Object。
$ b 发送的Object(称为items)是一个对象列表,它有一个名为Item的特定类(prototype)。
这里有一些代码:
//在background.html
chrome.tabs.create({ index:0,url:results.html},function(tab){
chrome.tabs.sendRequest(tab.id,{'items':itemsList},function(response){
console .log(response.farewall);
});
});
另一方面,在新创建的页面中,我收到发送的对象
// newpage.html
chrome.extension.onRequest.addListener(
函数(request,sender,sendResponse){
console.dir(request.items);
sendResponse({});
}
);
问题在于,当我收到对象列表时,在 newpage .html
,对象类型丢失。事实上,在新的后台页面
中使用 console.dir()
时, itemsList 已正确报告,但不在 newpage.html
中的收到物品清单对象中。我可以手动通过字符串手动序列化< newpage.html
进行反序列化,但是我想知道是否有更好的方法来支付这个费用,并防止列表中的对象类型(即Item)丢失。
在通过请求传递对象时,Chrome会要求它为JSON序列化,这意味着它在传输之前被编码为JSON字符串,作为字符串传输,然后解码回来。而JSON不支持函数序列化。
I'm working on a Chrome extension and I've the following problem.
When a certain event happens, my background page creates a new tab (page) with chrome.tabs.create
API and send an Object.
The sent Object (called items) is a list of objects, having a particular class (prototype) called Item.
Here some code:
// in background.html
chrome.tabs.create({index: 0, url: "results.html"}, function(tab) {
chrome.tabs.sendRequest(tab.id, {'items': itemsList}, function(response) {
console.log(response.farewall);
});
});
On the other hand, in the newly created page, I receive the sent objects
// newpage.html
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.dir(request.items);
sendResponse({});
}
);
The problem is that, when I receive the objects list, in the newpage.html
, the Object type is lost. Indeed using console.dir()
in the new background page
, the objects type in the itemsList is correctly reported, but not in the received items list object in newpage.html
.
I could manually serialize the data in he background.html
manually through a string, and manually de-serialize in newpage.html
but I would like to know if there is a better way to afford this and prevent that objects type (namely Item) in the list is lost.
When passing an object through a request, Chrome requires it to be "JSON-serializable", which hints that it is encoded to JSON string before the transfer, transferred as a string, and then decoded back. And JSON doesn't support function serialization.
这篇关于对象类型在消息传递中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!