2010-12-20 2 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'

は、私がここで間違って何をしているのですか?
ありがとうございます! JSONにデータをシリアライズ

答えて

1

Google Chrome Message Passing mechanism作品:

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式に変換できないため、失われます。残念ながら、それは静かに失敗し、オブジェクトの残りのプロパティが正しくなると混乱します。シリアライズ

関連する問題