0

I'm working on a chrome extension that uses an Event Page and I'm trying to completely clear it's local storage every time Chrome starts up.

This is what I have right now in eventPage.js:

chrome.runtime.onStartup.addListener(function() {
  chrome.storage.local.clear(function() {
    var error = chrome.runtime.lastError;
    if (error)
      console.error(error);
  });
});

// The below code retrieves the object of interest 'storage_var' 
// and does stuff with it

chrome.storage.local.get(init);

function init(storage_var) {
  // doing stuff, includes a bunch of listeners and helpers that
  // sometimes use chrome.storage.local.set to affect local storage
}

This does not seem to be working. I understand the asynchronous nature of these functions, so please spare me any long lectures about them. This isn't an attempt to somehow make the clear function behave synchronously; I'm not just not sure how I can use the clear function properly so it does as intended.

I was thinking about putting everything below the chrome.runtime.onStartup.addListener call in the callback function of clear so that it only gets called after the clear has finished, but this would mean putting essentially the whole program in the chrome startup listener, which doesn't seem like the right approach. I'm just not sure I'm thinking about this the right way.

Any help and wisdom about asynchronous functions would be appreciated. Please no rants though, I've already read plenty :) Thank you!

applemavs
  • 503
  • 3
  • 9
  • 22
  • I'm very surprised that this would even be allowed by Chrome in the first place. – Scott Marcus Jul 28 '17 at 23:52
  • 1
    For what you want, put the entire program flow which depends on the storage being clear in the callback for `chrome.storage.local.clear()`. That's how asynchronous functions work. You don't have to define all your functions there (i.e. you can have functions and variables defined in the global scope), but your execution flow needs to be in the callback. – Makyen Jul 29 '17 at 00:17
  • @ScottMarcus Why do you say that? – applemavs Jul 29 '17 at 01:22
  • @Makyen But wouldn't that mean my control flow would all be contained within the `chrome.runtime.onStartup` listener? This is an event page, so in the future it may be unloaded and loaded again; if everything is within the onStartup listener, won't it only be accessible upon startup and thus inaccessible in the future when it gets unloaded/loaded? – applemavs Jul 29 '17 at 01:30
  • Then you have it in a single `init()` function which you choose to execute, or not, in the alternate flow. Without knowing your complete requirements, we can't say exactly how to do it. But, if you want the storage cleared when it executes, then it needs to be in the `storage.local.clear()` callback. – Makyen Jul 29 '17 at 01:41
  • @applemavs, see [Chrome extensions - runtime.onStartup before any other actions](//stackoverflow.com/a/33160051) – wOxxOm Jul 29 '17 at 04:54

0 Answers0