Search code examples
javascriptjquerygoogle-chromegoogle-chrome-extensionsession-storage

Clear session and local storage for specific domain from a chrome extension


Is it possible to clear session and local storage for specific domain from a chrome extension?

Let's say I want to target the sessionStorage or localStorage for somedomain.com. The way I do this now is:

function clearSessionSotorage(key) {
  /**
   * Clears the session storage value for the given key
   * @param string key The key whose value should be cleared, if not provided, all keys are cleared for the current domain
   */
   var code = key ? 'window.sessionStorage.clear(' + key + ')' : 'window.sessionStorage.clear()';
   chrome.tabs.executeScript(null, { code: code });
}

function clearLocalStorage(key) {
  /**
   * Clears the local storage value for the given key
   * @param string key The key whose value should be cleared, if not provided, all keys are cleared for the current domain
   */
  var code = key ? 'window.localStorage.clear(' + key + ')' : 'window.localStorage.clear()';
  chrome.tabs.executeScript(null, { code: code });
}

This works as long as the active tab is open to a page on somedomain.com.

However, I'd like to target specific domains without the need to have that domain up in the active tab.

If it's possible, how can I do this?

I've considered cycling through all tabs looking for the target url, which would be an improvement, but really, I'd prefer an option that avoids having to have the domain active at all.


Solution

  • I believe the only way is to loop all tabs and look for the target url, then remove the sessionStorage for that domain, or if you want, you can insert content scripts for specific domain, which would do clear sessionStorage logic.

    When you said

    I'd prefer an option that avoids having to have the domain active at all

    It seems you forgot the lifecycle of sessionStorage, according to Window.sessionStorage, sessionStorage would be cleared when the tab/browser closed and won't be shared between tabs.

    Opening a page in a new tab or window will cause a new session to be initiated