I want to be able to store data on background (on my extension) so I can access this data between multiple domains.
Where\'s what I\'m doing:
content-scr
background-script.js:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch (request.command) {
case 'setItem':
localStorage[request.name] = JSON.stringify(request.data));
return;
case 'getItem':
var retValue;
if (typeof(localStorage[request.name]) === 'string') {
retValue = JSON.parse(localStorage[request.name]);
}
sendResponse(retValue);
return;
case 'deleteItem':
if (typeof localStorage[request.name] !== 'undefined') {
delete localStorage[request.name];
}
return;
}
});
If the key is not in the localStorage, getItem will return undefined
. Instead of defining the function getItem
the way you did, you should send a message to the background with a callback and then do something with the value when the callback is called. You can't return the value from the function getItem
, but you can use the value in the callback when it is called:
function getItem(name, callback) {
chrome.extension.sendMessage({command: 'getItem', name: name}, function(response) {
if (typeof(callback) === "function") {
callback(response);
}
});
}