简体   繁体   中英

javascript localStorage.clear() on code update

The concept seems simple, but implementation logic seems daunting right now.

I use localStorage in my app, and I want to clear it when I update the code.

Any ideas how?

You could store the code version in the script and compare that when you load the script:

var version = "1.0.4"; // remember to update this
if(localStorage.getItem("version") != version){
  localStorage.clear();
  localStorage.setItem("version", version);
}

$(function(){
  ...

If you don't want to track the version manually, you can generate the "version" by hashing the script. A good hash is a balance between ease of implementation (this kinda rules out MD5, unless you're willing to fetch a library), hash size (you don't want to store a copy of the script in localStorage) and its detection capabilities (so the string length may not suffice).

Needless to say, deleting all storage with any single change may be too cautious, so I recommend the manual version tracking approach, or (better yet) refactor the application so that it can work with the previous version data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM