最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clear session and local storage for specific domain from a chrome extension - Stack Overflow

programmeradmin5浏览0评论

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. 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.

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.

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.. 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..

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.

Share Improve this question edited Mar 25, 2016 at 8:53 Wesley Smith asked Mar 25, 2016 at 8:07 Wesley SmithWesley Smith 19.6k22 gold badges91 silver badges134 bronze badges 10
  • I don't think you can do that as you're blocked by Same Origin Policy. Scripts in pages loaded from domain1 cannot access storage objects from domain2. – Arkantos Commented Mar 25, 2016 at 8:15
  • 1 @Arkantos this is a chrome extension, it does not have this restriction... – smnbbrv Commented Mar 25, 2016 at 8:16
  • @smnbbrv exactly, a lot of things are possible in this context that are not in a normal page. Im hoping this is one of those, nice catch on the edit BTW – Wesley Smith Commented Mar 25, 2016 at 8:17
  • @smnbbrv.. Good to know that. it would be helpful if you can provide some link explaining that. :) – Arkantos Commented Mar 25, 2016 at 8:19
  • @DelightedD0D, As mentioned here, clear() will not accept any arguments and clears all storage items. If you want to remove a specific item from storage based on a key, use sessionStorage.removeItem(key) instead – Arkantos Commented Mar 25, 2016 at 8:20
 |  Show 5 more ments

4 Answers 4

Reset to default 2

If you wish to clear sessionStorage/localStorage for a particular domain that is currently opened but not active in your browser window, then you need to execute some script in the context of that domain.

I think you can do this using a ibination of chrome.tabs.query()(link1) and then chrome.tabs.executeJavaScript()(link2) using code as string or using name of Content Script file.

chrome.tabs.query({
  'url' : 'target-domain.'
});

chrome.tabs.executeScript({
    code: 'sessionStorage.clear()'
  });

(or)

chrome.tabs.executeScript(null, {file: "content_script.js"});

For url property in tabs.query(), you can use patterns as mentioned here;

As already pointed, there is a way with tabs where you can open a tab and run the code in there. But opening / closing tabs does not really sound a good solution...

After some investigation I have a small and quite working solution using IFRAME instead of tabs. Add this code to your background.js:

// create a URL suffix to make it unique and make nearly impossible to hit the existing page
var suffix = 'chrome-run-on-domain-' + chrome.runtime.id;

// if the domain is blocking displaying pages in IFRAME, remove the restriction
chrome.webRequest.onHeadersReceived.addListener(function(details) {
  return {
    responseHeaders: details.responseHeaders.filter(function(e) {
      return e.name.toUpperCase() !== 'X-FRAME-OPTIONS';
    })
  };
}, { urls: [ '*://*/' + suffix ] }, ["blocking", "responseHeaders"]);

// finally the function which does the job: it adds an IFRAME to the background page
function injectScript(protocol, domain) {
  var iframe = document.createElement("iframe");

  iframe.src = protocol + '://' + domain + '/' + suffix;

  document.body.appendChild(iframe);
}

// run the code
injectScript('https', 'www.google.de');

This code already makes a big chunk of the job. It creates an iframe on your background page which securely es to the domain of your wish.

Then you need to create a file with changes you want to run on a page:

// actually any action to do with a session/localStorage
sessionStorage.clear();
localStorage.clear();

// important, stops the page loading
// this prevents unnecessary images / css / js calls on that page
// and prevents js redirects
window.stop();

Now it's time to set the references and permissions in your manifest file:

"background": {
  "scripts": [
    "background.js"
  ]
},
"content_scripts": [{
  "all_frames": true,
  "js": ["injectable.js"],
  "matches": ["*://*/chrome-run-on-domain-*"],
  "run_at": "document_start"
}],
"permissions": [
  "<all_urls>",
  "webRequest",
  "webRequestBlocking"
]

What you have in the end: you can clear the localStorage, and not only. You don't open new tabs for that, so it goes quite smoothly. Still there are disadvantages (still the same problems will be existing on tabs solution):

  1. there is no server side redirect (301 / 302 / etc) protection. If server will response with a redirect, it cannot really be intercepted.
  2. there is still a server call. I tried to cancel the request (if that would work, there were no disadvantages at all) but unfortunately chrome does not allow to inject script into the cancelled request. window.stop() helps here but still...

It works even better with your initial method: you simply check first your tabs whether there is a page from your domain and if there is none use the method above.

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

If your localStorage is ing from an iFrame, you can clear it by rubbing this code on your console.

$('.my_iframe')[0].contentWindow.localStorage.clear();
发布评论

评论列表(0)

  1. 暂无评论