I’m using simple custom type in content script of chrome extension. Array of items then sent to background page via chrome.extension.sendRequest(). In bgpage debugger shows that instances of my type don’t have these methods. Also, the same happens with type properties with undefined values. What’s wrong.
function User(id, holder) {
this.id = id;
var hObj = {};
hObj[holder] = 'undefined'; // this is ok
this.holder = hObj;
this.Result = undefined; // this will be lost
this.Code = undefined; // this will be lost
}
// this will be lost
User.prototype.getFirstHolderType = function() {
for (h in this.holder) {
if (h) return h;
}
return false;
};
// this will be lost
User.prototype.hasHolderType = function(h_type) {
for (h in this.holder) {
if (h_type === h) return true;
}
return false;
};
//...
chrome.extension.sendRequest({id: "users_come", users: users},
function(response) {});
Message passing uses
JSON.stringify, which drops functions from objects when it stringifies them.Why? A function is much more than just code — it’s a closure with loads of variable/scope information. If a function uses a global variable and the function gets move to a new execution environment, how should it behave? (In fact, the question is much for profound than “how should it behave?”, it’s more like “how could all of the variables in scope within the function be transported along with the function?”.)
If you want to transport your function code (and know in advance that necessary variables will exist at the destination), you can use
toStringon your member functions to transport them a strings and use andevalto re-create them on arrival.(
JSON.stringifyalso drops members that have anundefinedvalue. For example,JSON.stringify({"a":undefined})yields"{}". If you want these values to be preserved, set them tonull. A member variable set toundefinedis indistinguishable from a member variable that was never set at all.)