chrome local storage extension code example
Example 1: how to store edited data of chrome extension locally
{
"permissions": [
"storage"
]
}
chrome.storage.sync.set({ "yourBody": "myBody" }, function(){
});
chrome.storage.sync.get(["yourBody"], function(items){
});
chrome.storage.local.set({ "phasersTo": "awesome" }, function(){
});
chrome.storage.local.get(["phasersTo"], function(items){
});
Example 2: sotre json on chrome storage
var local = (function(){
var setData = function(key,obj){
var values = JSON.stringify(obj);
localStorage.setItem(key,values);
}
var getData = function(key){
if(localStorage.getItem(key) != null){
return JSON.parse(localStorage.getItem(key));
}else{
return false;
}
}
var updateDate = function(key,newData){
if(localStorage.getItem(key) != null){
var oldData = JSON.parse(localStorage.getItem(key));
for(keyObj in newData){
oldData[keyObj] = newData[keyObj];
}
var values = JSON.stringify(oldData);
localStorage.setItem(key,values);
}else{
return false;
}
}
return {set:setData,get:getData,update:updateDate}
})();
Example 3: store current date in chrome storage extension
const currentTime = (new Date()).toJSON();
const items = { 'testdate': currentTime };
chrome.storage.local.set(items, () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
chrome.storage.local.get(['testdate'], (result) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
} else {
const storedJSONDate = result['testdate'];
const testdate = new Date(storedJSONDate);
console.log(testdate);
}
});