Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.storage.sync.set variable key

I am writing a chrome extension that will be using the chrome storage API. I am trying to use a variable for the key and set the value to null:

function save() {
    var item = $("#item").val();
    chrome.storage.sync.set({item:null}, function(){
        console.log("sync settings saved");
    });
}

I am then running the following to view all saved data:

chrome.storage.sync.get(null, function(items) {
    console.log(items);
});

The console output is:

Object {item: ""}

So basically it is getting set, but instead of saving it with the value of the variable it is saving it with the variable name.

Any ideas how to get it to save the variable value instead?

like image 801
dtascher Avatar asked Dec 29 '14 20:12

dtascher


People also ask

Can Chrome extensions Read localStorage?

Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage. Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing. chrome.

How does Chrome local storage work?

localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.


1 Answers

It's expected behavior in JavaScript. It is how you define keys in Objects.

If you want to set a variable value as an object key you can do something like:

var item = $("#item").val();
var save = {};
save[item] = null;
chrome.storage.sync.set(save)
//...

Then save object will not use "item" as a key but it's value.

like image 52
Pawel Psztyc Avatar answered Sep 20 '22 05:09

Pawel Psztyc