开发者

dispatchMessage and associative arrays

开发者 https://www.devze.com 2023-01-29 10:36 出处:网络
I have a problem delivering assiciative arrays to an injected script. Global.html var settings = new Array();

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?


  1. You're using arrays when you should be using objects.

    var settings = new Array();  // Wrong
    var settings = {};           // Right (and better than "new Object()")
    
  2. 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";).

  3. 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
    
0

精彩评论

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