DEV Community

Karthikeyan Dhanapal
Karthikeyan Dhanapal

Posted on

How to save values in Chrome local storage

How to save a variable locally inside the Chrome browser's local storage?
And this is one of the combinations that I used to search on google to get the answer.

And guess what? Being a noob in the field of chrome extension development, I faced a hard time in understanding the concept explained in the chrome extension development documentation. Finally, I landed up in a youtube channel, that(https://www.youtube.com/watch?v=DHP2h_7mOfA) explained the process. This guy is kind of the person who explained the concept as you explain it to a 5-year-old and he is good at it. Thanks to him.

So here I am trying to explain the same thing in a simple way, so that if anyone faces the problem in the future. Just in case.

First, you need to set the value of the variable that you wish to save in order to retrieve it.

So we use the following method to save.


chrome.storage.sync.set({'variable_name': 'variable_value'}, function() {
  console.log("you saved me!!");
});

Enter fullscreen mode Exit fullscreen mode

here, the 'set' method sets the value of the variable called 'variable_name' in the local storage.

In order to retrieve it, you need to use the 'get' method instead of 'set'.


chrome.storage.sync.get(['variable_name'], function(result) {
      if(result.variable_name == undefined) {
        console.log("I am retrieved!!");
      }
}

Enter fullscreen mode Exit fullscreen mode

The following will retrieve the value of 'variable_name' as an object. So in order to access it, you need to use the object name followed by the variable name. (i.e)

result.variable_name
Enter fullscreen mode Exit fullscreen mode

and the reason why we are checking for the undefined is kind of a fail-safe. This is not covered in the documentation.

The scenario for this fail-safe would be, consider your extension is developed with the use of local storage of a variable called

'local_variable'
Enter fullscreen mode Exit fullscreen mode

but when the user tries to open the extension for the first time in a browser it will throw an

undefined - error 
Enter fullscreen mode Exit fullscreen mode

this is because the variable is not yet defined in the user's local storage.

So this fail-safe will come in handy at that time. You can add an extra condition as this so that it won't break your code and your user's heart 😜.

Top comments (0)