jblz
jblz

Reputation: 1029

Clearing Chrome extension localStorage from within popup.js

I have everything in my extension working apart from one thing! I want to clear the local storage of this extension through popup.js. It's a simple extension that saves form data from a certain domain.

Currently, in my content script (save.js) I'm accessing local storage through localStorage[key] however it seems I'm unable to do this through popup.js and I get an 'undefined' which I assume it expected behaviour.

I have tried localStorage.clear(); from my popup.js but this has no effect. Presumably because it's looking to clear non existent localStorage from within the extension itself?

How can I access and clear the local storage that my save.js has been using from popup.js?

popup.js

document.getElementById('clearAllData').addEventListener('click', clear);

function clear(){
	localStorage.clear();
 }
 
 

Snippet of how I'm saving data in save.js

function saveTicket(ticket, contents) {
	localStorage[ticketID] = contents;
}

Upvotes: 0

Views: 3008

Answers (2)

Daniel Herr
Daniel Herr

Reputation: 20478

You should use chrome.storage instead of localStorage. When you use localStorage in a content script, is it of the page, not of your extension. However, when you use chrome.storage in a content script, it is the storage of your extension.

Upvotes: 0

Mifune
Mifune

Reputation: 128

You're not using the callback correctly. You need to pass the function asynchronously. For example:

function clear(){
   chrome.storage.local.clear(function(obj){
      console.log("cleared");
      });
 }

however it might be this as well. Chrome storage is already local.

function clear(){
   chrome.storage.sync.clear(function(obj){
      console.log("cleared");
      });
 }

Upvotes: 3

Related Questions