saving and retrieving from chrome.storage.sync

JavascriptGoogle ChromeGoogle Chrome-Extension

Javascript Problem Overview


I am trying to save a data object in chrome sync storage and then retrieve it, however the get() function always returns an empty object. The code I am using is,

function storeUserPrefs() {
	var key='myKey', testPrefs = {'val': 10};
        chrome.storage.sync.set({key: testPrefs}, function() {console.log('Saved', key, testPrefs);});
}

function getUserPrefs() {
	chrome.storage.sync.get('myKey', function (obj) {
		console.log('myKey', obj);
	});
}

Could someone please tell me what I am doing wrong here?

Javascript Solutions


Solution 1 - Javascript

The problem is with chrome.storage.sync.set({key: testPrefs}

Your data is stored as

{
    key: "{"val":10}"
}

So, your code chrome.storage.sync.get('myKey') return undefined\empty object.

Solution I

Use string "key" as your key

chrome.storage.sync.get("key", function (obj) {
    console.log(obj);
});

or

Solution II

Set data through "myKey" Key.

chrome.storage.sync.set({"myKey": testPrefs})

P.S : Don't forget chrome.storage.sync is permanent storage API, Use chrome.storage.sync.clear before any further testing to see changes

References

EDIT 1

Use this code to set variable value in Chrome.storage

function storeUserPrefs() {
    var key = "myKey",
        testPrefs = JSON.stringify({
            'val': 10
        });
    var jsonfile = {};
    jsonfile[key] = testPrefs;
    chrome.storage.sync.set(jsonfile, function () {
        console.log('Saved', key, testPrefs);
    });

}

It generates following Output

Object{
    myKey: "{"val":10}"
}

Solution 2 - Javascript

A more fancy way to do it, and it handles errors as well:

const getStorageData = key =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.get(key, result =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve(result)
    )
  )

const { data } = await getStorageData('data')


const setStorageData = data =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.set(data, () =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve()
    )
  )

await setStorageData({ data: [someData] })

Solution 3 - Javascript

function storeUserPrefs() {
    var key='myKey', testPrefs = {'val': 10};
    chrome.storage.sync.set({[key]: testPrefs}, function() {
      console.log('Saved', key, testPrefs);
    });
}

You could just force to evaluate the variable key using [key] when saving. That way is easy to set your keys dynamically. Hope that helps.

Solution 4 - Javascript

As chrome.storage.sync can storage JS objects, you can just do this:

var save = {};
save["myKey"] = testPrefs;

chrome.storage.sync.set(save, function() {
    console.log('Settings saved');
});

Solution 5 - Javascript

testPrefs = JSON.stringify({
            'val': 10
        });
    var jsonfile = {};
    jsonfile[key] = testPrefs;
    chrome.storage.sync.set(jsonfile, function () {
        console.log('Saved', key, testPrefs)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsource.rarView Question on Stackoverflow
Solution 1 - JavascriptSudarshanView Answer on Stackoverflow
Solution 2 - Javascriptbde-mazeView Answer on Stackoverflow
Solution 3 - JavascriptdanieluyView Answer on Stackoverflow
Solution 4 - JavascriptEneas GesingView Answer on Stackoverflow
Solution 5 - Javascriptuser3018868View Answer on Stackoverflow