2010-12-20 86 views
1

我的擴展程序在後臺頁面中創建一個對象,並將該對象中的所有配置變量存儲在所有
之間。目的是共同爲
所有內容腳本,因此後臺頁面將其發送到
內容腳本的連接請求被接收後:傳入鉻擴展中的對象

// 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: "forTimObject"});
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'

我在做什麼錯在這裏?
在此先感謝!

回答

1

Google Chrome Message Passing mechanism作品串行化數據到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).

如果一個對象是使用消息傳遞發送,這將是轉換爲JSON。因此,在「stringify」2時,方法「method1」丟失,因爲它無法轉換爲有效的JSON表達式。不幸的是,它失敗了,並且由於對象的其餘屬性是正確的序列化。