How to build a Chrome extension, Part 2: Options and localStorage

An important aspect of almost all extensions is being able to save user settings. This can be achieved in Chrome easily by using the localStorage object and Chrome’s extension API options page.

Adding an options page

To add an options page to your extension, make an options.html file in your extension’s folder and add the “options_page” line to your manifest.json like so:

{
  "name": "My Extension",
  ...
  "options_page": "options.html"
  ...
}

localStorage

localStorage is an HTML5 object used for storing web page data locally using JavaScript. Chrome gives extensions the option of using localStorage to save options and data.

Saving options

To save a string to localStorage, use the following code, replacing mysetting and myvalue with your own:

localStorage["mysetting"] = "myvalue";

Or, equivalently:

localStorage.mysetting = "myvalue";

Loading options

To load an option, just access the setting member in the localstorage object:

myvar = localStorage["mysetting"];

Or, equivalently:

myvar = localStorage.mysetting;

It’s always a good idea to make sure you’ve loaded a valid setting. For example, the following code loads a favorite color, but if the current color is not valid, it loads the default value:

var defaultColor = "blue";

function loadFavColor() {
	var favColor = localStorage["favColor"];

	// valid colors are red, blue, green and yellow
	if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
		favColor = defaultColor;
	}

	return favColor;
}

Erasing options

You can erase an option by removing it from the localstorage object, like so:

localStorage.removeItem("mysetting");

Building an options page

Continuing with the favorite color example, lets now build a complete options page for our color-choosing extension. The options.html page would look like this:

<html>
<head>
	<title>Options for Color Chooser</title>
	<script type="text/javascript" src="options.js"></script>
</head>
<body onload="loadOptions()">
	<h1>Favorite Color</h1>
	<select id="color">
		<option value="blue">Blue</option>
		<option value="red">Red</option>
		<option value="green">Green</option>
		<option value="yellow">Yellow</option>
	</select>
	<br />
	<button onclick="saveOptions()">Save</button>
	<br />
	<button onclick="eraseOptions()">Restore default</button>
</body>
</html>

For the behavior of the page, options.js would look like this:

var defaultColor = "blue";

function loadOptions() {
	var favColor = localStorage["favColor"];

	// valid colors are red, blue, green and yellow
	if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
		favColor = defaultColor;
	}

	var select = document.getElementById("color");
	for (var i = 0; i < select.children.length; i++) {
		var child = select.children[i];
			if (child.value == favColor) {
			child.selected = "true";
			break;
		}
	}
}

function saveOptions() {
	var select = document.getElementById("color");
	var color = select.children[select.selectedIndex].value;
	localStorage["favColor"] = color;
}

function eraseOptions() {
	localStorage.removeItem("favColor");
	location.reload();
}

And that’s about it! You can also save and load localStorage data elsewhere in your extension, as the data is shared between all your extension’s files.

Any question, remark, or addition? Please leave a comment!

  • Aditya

    Wow… I am seeing this as it is being posted… I am excited.. :D

  • Pingback: How to build a Chrome extension, Part 3: Loading any web page in a popup « Juliana Peña

  • Shai

    1. option.js is missing “)” in th validation line
    2. I get a “localstorage is not defined” exception from code

  • http://julianapena.com Juliana Peña

    How are you running the extension? Use Chrome's 'Load unpacked extension' option.

  • Shai

    I got it working, I copied the code from here and it has a typo, it should be localStorage, capital 'S'
    + the missing “(“

  • http://julianapena.com Juliana Peña

    Whoops, you're right. Sorry for the typo. It should be correct now. :)

  • Pingback: Cómo hacer una extensión de Chrome, Parte 2: Opciones y localStorage | Hogargeek

  • Ty

    I'm not entirely sure that the localStorage data is shared between extension pages. I have set localStorage values in my extension's options page, but the data is not visible to the popup page (which is where I need the options to show up!)

    My two theories are that either popup pages do not have the same privileges, and can't access the data, or that the data is not shared while the extension is unpacked. I intend to test these theories.

  • Ty

    After a small bit of testing, I can see that localStorage values are shared between extension pages. Mostly.

    I know from my testing that localStorage is shared between (at least) the options page and the background page. I know from documentation that the data from those pages is not shared with content scripts. And I know that it's not showing up in my popup pages, either.

    I suppose this means that popup pages don't have easy access to localStorage settings. I find this to be quite problematic, and to be honest, it bothers me.

    Okay, I'm done talking to myself. :)

  • bryanlynn

    This is pretty powerful. I tried to use pieces of this, but I think if I had a zipped version that worked it might be easier.

    • http://julianapena.com Juliana Peña

      Just use localStorage["myvalue"] or localStorage.myValue

  • Mike

    This issue is covered in http://code.google.com/p/chromium/issues/detail… — I am annoyed myself. I will have to try some of their workarounds.

  • Mike

    This issue is covered in http://code.google.com/p/chromium/issues/detail?id=42811 — I am annoyed myself. I will have to try some of their workarounds.

  • iampriteshdesai

    I want to store the url of the current tab into a variable in the popup.html page…
    how can i do it?

  • Rcha

    Would you know how to save image files into local storage?
    I want to add a feature where users can save a couple of image files into the options panel, and I would use those image files as arguments to a POST request I will be doing.
    I haven’t found any documentation on file storage. Only on text storage. Could you please guide me.
    Thank You.

    • http://julianapena.com Juliana Peña

      You could convert the images into base64 and save that as text.

  • http://profiles.google.com/ivanca Ivan Castellanos

    Gracias por la info! por aqui otro colombiano… but you probably already forgot how to speak spanish xD

  • Jayapal Chandran

    I was trying to store boolean and integers but it always showed as string when in used typeof…
    for example window.localStorage.theflag = true or window.localStorage = false and i use a condition like the following if(window.localStorage.theflag) always gives true because when i alerted with type of it showed that as string and not as integer or boolean … how do we use integer data in localstorage … ? do we have to typecase or need to multiply with *1 to make the result an integer data type ???

  • http://suanaikyeo.com suan

    Thanks so much for posting this. Information about chrome options pages is surprisingly hard to find!

  • http://wizkidsound.com Robert Dyson

    Thanks for this! Very useful. 

  • Aaron Frost

    The second to last line what the exact piece of info I was looking for. Thanks!

  • hugo lpz

    Juliana, thanks for this clear tutorial which as far as I know it the best I found for a quick extension tutorial. I have a begginer question. Upper is how look the options page’s code to save the id=color ‘s value=fav_color within the localStorage, ok. Can you also publish an exemple of the .html/.js/.css code which will *USE* this localStorage ? That will complete your page.
    PS: I also post your tutorial to the wikipedia’s communauty : ) (I’m wikipedian)

  • Eion

    So how do i call for the local storage value that i stored within my popup.html page?

    • Aaronfrost

      Just use localStorage["myvalue"] or localStorage.myValue

  • 文 齐

    Thanks,  Juliana, it’s helpful~~

  • Felix Schliemann

    Very helpful. Thank you for this nice article!

  • klipo

    hi juliana! First of all, 10x for tutorial. I’m gonna ask u something. u are using localstorage for keeping data, but how long is it active as data? i mean, is it possible that can be remove by client?

    • http://julianapena.com Juliana Peña

      The data will be there until it is deleted. The user can delete it manually by going to menu > tools > clear browsing data, or by using the web inspector’s resources tab.

    • klipo

      10x

  • Claudio “Crius” Vallesi

    Can you explain me how you can make this page work while the “manifest.json” type “2″ do not allow direct js inside the html page.

    I’m referring to the onload event and onclick event just.
    Actually every try give me the following error:
    Refused to execute inline event handler because it violates the following Content Security Policy directive: “script-src ‘self’ chrome-extension-resource:”.

  • whatever

    You just copied this tutorial right off of Googles tutorial page “word for word”. And you are trying to pass yourself off as a developer?

  • Shuresh Kumar

    Nice article :) But want to open the popup.html in a New tab i.e) Page Action

  • Vanderson Silva

    Can we sync the data saved on other chromes browsers? I heard that chrome has it’s own local storage api…would it be better to use the chromes api?

  • MikeyP

    How would you enter a .png image above the in the options page

  • Aayush Rathi

    then how to use
    chrome.storage.local.get(‘varName’,function() { …..});
    and store variables through this method