I have a problem delivering assiciative arrays to an injected script.
Global.html
var settings = new Array();
settings["accountID"] = safari.extension.settings.getItem("accountID");
settings["accountName"] = safari.extension.settings.getItem("accountName");
settings["accountEmail"] = safari.extension.settings.getItem("accountEmail");
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("settingsArray", settings);
script.js
switch (msgEvent.name) {
case "settingsArray":
var settings = new Array();
开发者_如何学编程 settings = msgEvent.message;
console.log("accountID: " + settings["accountID"]);
break;
When I do it with "normal" arrays, it works fine!
But when delivering associative arrays, I always get "undefined" when calling eg. settings["accountID"]
Does anyone have an idea what's wrong?
You're using arrays when you should be using objects.
var settings = new Array(); // Wrong var settings = {}; // Right (and better than "new Object()")
You are unnecessarily using the string form of property access.
settings["accountID"] = …; // Works, but too much typing settings.accountID = …; // Exact same functionality
You only need to use the bracket notation when getting/setting property values if the property name is not a valid JavaScript identifier (e.g.
foo["holy!*#$! it works"] = true
) or if you need to construct the property name from a variable (e.g.foo["account"+n] = "active";
).You are creating new objects and then throwing them away.
var settings = new Array(); // Makes a new array referenced by a variable settings = msgEvent.message; // Discards the array and changes the variable // to reference a new object
精彩评论