JSON.parse returns a string instead of an array

I have a javascript array that I am building to save it in localstorage

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

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

After extracting it and parsing it back to JSON

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

The returned length is 342, which is the length of the entire string. I tried to get the type of an object through the constructor.name property, it gives me a string instead of Array .

Any ideas on what's 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(); }); 
+4
source share
1 answer

You need to use this query - chrome.extension.sendRequest({message: "setKeywords"... but for getKeywords . The getItem function cannot be used to access the background page variable.

+1
source

All Articles