How can I save information locally in my chrome extension?

JavascriptGoogle ChromeGoogle Chrome-Extension

Javascript Problem Overview


I want my chrome extension to save some information, and I'm not sure how to start the code... I need it to save strings. For example - The user inputs a string (In a text area over the popup) and this string is shown on the popup. When the user exits it and returns I want the string to remain the same. (I belive it has to save it) I don't want to save it on my server or anything like that, I want it to be saved on the users cache or something.

Javascript Solutions


Solution 1 - Javascript

You can now leverage Google Chrome's storage API to do this as well. Unlike localStorage, this is accessible from content scripts as well.

//	Somewhere in your manifest...

{
	"permissions": [
		"storage"
	]
}

//	Usage:

//	PERSISTENT Storage - Globally
//	Save data to storage across their browsers...

chrome.storage.sync.set({ "yourBody": "myBody" }, function(){
	//	A data saved callback omg so fancy
});

chrome.storage.sync.get(/* String or Array */["yourBody"], function(items){
	//	items = [ { "yourBody": "myBody" } ]
});

// 	LOCAL Storage

// Save data to storage locally, in just this browser...

chrome.storage.local.set({ "phasersTo": "awesome" }, function(){
	//	Data's been saved boys and girls, go on home
});

chrome.storage.local.get(/* String or Array */["phasersTo"], function(items){
	//	items = [ { "phasersTo": "awesome" } ]
});

More info on how these shenanigans work here: https://developer.chrome.com/extensions/storage#type-StorageArea

Former answer:

Use localStorage. Google Chrome implements some features of HTML5, and it is one of them.

//Pull text from user inputbox
var data = document.getElementById("this_input").value;
//Save it to the localStorage variable which will always remember what you store in it
localStorage["inputText"] = data; 

You should note you can only access your storage from the background page (no content scripts) so you'll have to use messaging for that.

Solution 2 - Javascript

There is a specific API now, check this here: https://developer.chrome.com/extensions/storage

Note that it is only available on your background page and works in an isolated world (you don't access the values contained in the HTML5 localStorage of the web site).

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
QuestionArielView Question on Stackoverflow
Solution 1 - JavascriptmattsvenView Answer on Stackoverflow
Solution 2 - JavascriptBeauCielBleuView Answer on Stackoverflow