DEV Community


How to save values in Chrome local storage

chintukarthi profile image Karthikeyan Dhanapal ・2 min read

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( 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.{'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'.['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)

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

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 😜.

Discussion (0)

Editor guide