开发者

Object passing in chromium extension

My extension creates an object in the background page and stores all

the configuration variables in that object. The object is common for

all content scripts and hence the background page sends it to the

content scripts after a connection request is received:

// In background.html

timObject = {

property1 : "Hello",

property2 : "MmmMMm",

property3 : ["mmm", 2, 3, 6, "kkk"],

method1 : function(){alert("Method had been called" +

this.property1)}

};

chrome.extension.onConnect.addListener(function(port) {

console.assert(port.name == "forTimObject");

port.postMessage({object:timObject});

});

// Now in content script:

var extensionObject = null;

var port = chrome.extension.connect({name: "forTi开发者_运维问答mObject"});

port.onMessage.addListener( function(msg) {

if (msg.object != null)

extensionObject = msg.object;

else

alert("Object is null");

} );

alert(extensionObject.property1); // This is ok, alert box is displayed with the right contents

alert(extensionObject.method1) //Uncaught TypeError: Object # has no method 'method1'

What am I doing wrong here?

Thanks in advance!


Google Chrome Message Passing mechanism works serializing data to JSON:

Communication between extensions and their content scripts works by using message passing [...] A message can contain any valid JSON object (null, boolean, number, string, array, or object).

If an object is sent using message passing, it will be convert to JSON. So, at the time of the "stringify]2ing the method "method1" is lost as it cannot be transformed into a valid JSON expression. Unfortunately, it fails silently and it is confusing as the rest of the properties of the object are correctly serialized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜