JSON.parse返回字符串而不是Array

时间:2011-06-22 07:12:02

标签: javascript jquery json google-chrome google-chrome-extension

我有一个javascript数组,我将其字符串化,以便将其存储在localstorage

console.log(request.keywords.length);
localStorage.keywords = JSON.stringify(request.keywords);

其中关键字是javascript数组。这里request.keywords.length返回12,这是数组中元素的数量。

检索并解析回JSON后

 var keywords = chrome.extension.getBackgroundPage().getItem("keywords");
    var kjos=JSON.parse(keywords);
    console.log(kjos.length);

返回的长度是342,这是整个字符串的长度。我尝试通过constructor.name属性获取对象类型,它给了我string而不是Array

任何想法出了什么问题?

Snippets: Background.html

 function getItem(key) {
    var value;
    log('Get Item:' + key);
    try {
      value = window.localStorage.getItem(key);
    }catch(e) {
      log("Error inside getItem() for key:" + key);
      log(e);
      value = "null";
    }
    log("Returning value: " + value);
    return value;
  }

/////

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
localStorage.keywords = JSON.stringify(request.keywords);
}
);

//////////// Popup.js

var keywords = chrome.extension.getBackgroundPage().getItem("keywords");

    var kjos=JSON.parse(keywords); //kjos is a string variable

///// keywords.js

//keywordsArray is an Array object
    // Message passing to background page
        chrome.extension.sendRequest({message: "setKeywords", keywords: keywordsArray}, function() 
        {
            console.log(keywordsArray);
            console.log("message sent");
          // The data has been sent, we can close the window now.
          //window.close();
        });

1 个答案:

答案 0 :(得分:1)

您需要使用此类请求 - chrome.extension.sendRequest({message: "setKeywords"...,但需要getKeywords操作。函数getItem不能用于访问后台页面的变量。