开发者

JSON.parse returning string instead of Array

I have a javascript Array which I am stringifying in order to store it in localstorage

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

where keywords is javascript array. Here request.keywords.length returns 12 which is number of elements in array.

After retrieving it and parsing it back to JSON

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

The length returned is 342 which is the length of whole string. I tried getting type of object via constructor.name property, it gives me string instead of Array.

Any ideas what is going wrong ?

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();
        });


You need to use request like this - chrome.extension.sendRequest({message: "setKeywords"..., but for getKeywords operation. Function getItem can not be used for access to a variable of background page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜