chrome.storage.local.get and set

JavascriptGoogle ChromeGoogle Chrome-Extension

Javascript Problem Overview


I'm trying to use chrome.storage.local in my extension, and it doesn't seem to work. I used localStorage but realized that I can't use it in content scripts over multiple pages.

So, this is what I've come up with:

function save()
{
	var channels = $("#channels").val();
	var keywords = $("#keywords").val();
	
	chrome.storage.local.set({'channels': channels});
	chrome.storage.local.set({'keywords': keywords});
}

I do believe I'm doing the save() right, but the problem comes up in load():

function load()
{
	var channels = "";
	chrome.storage.local.get('channels', function(result){
		channels = result;
		alert(result);
	});
	
	var keywords = "";
	chrome.storage.local.get('keywords', function(result){
		keywords = result;
		alert(result);
	});
	
	$("#channels").val(channels);
	$("#keywords").val(keywords);
}

When the alerts trigger, it prints out [object Object]. Why is that? What am I doing wrong? I looked at the documentation/examples, but I can't seem to pinpoint the problem.

Javascript Solutions


Solution 1 - Javascript

This code works for me:

function load() {
    var channels = "";
    var keywords = "";
    chrome.storage.local.get('channels', function (result) {
        channels = result.channels;
        alert(result.channels);
        $("#channels").val(channels);
    });
} 

Chrome.storage.local.get() returns an object with items in their key-value mappings, so you have to use the index of the key in your search pattern.

IMP:

Thanks to Rob for identifying: Chrome.storage.local.get() is asynchronous, you should modify your code to ensure they work after callback() is successful.

Let me know if you need more information.

Solution 2 - Javascript

debug or use

alert(JSON.stringify(result));

for more details as to what you are getting back

Solution 3 - Javascript

The "result" value you are using is an object that contains the storage value, to get the value you have to use result.keywords, which will get the value of the keywords. EX:

function load(){
  chrome.storage.local.get('keywords', function(result){
    var keywords = result.keywords;
    alert(keywords);
  });

  chrome.storage.local.get('channels', function(result){
    var channels = result.channels;
    alert(channels);
  });
}

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
Questionuser569322View Question on Stackoverflow
Solution 1 - JavascriptSudarshanView Answer on Stackoverflow
Solution 2 - Javascript7zark7View Answer on Stackoverflow
Solution 3 - JavascriptMdbookView Answer on Stackoverflow