In mobile Web development, often use to localstorage to cache some data, in general, we need to follow the following code to use it will not be a problem.
if (window.localstorage) {
Localstorage.setitem (' key ', ' value ');
}
But just so judged is not enough, now some browsers have a function called no trace browsing , as the name suggests, is the user in the process of browsing the Web page, nothing is cached, nothing record, leaving no traces.
Naturally, Localstorage has also been disabled. But at this point window.localstorage is not NULL, it is still the original Localstorage object, but the method of this object is disabled. If you simply follow the above method to judge, JS throws an exception.
So you have to use the following code to determine if the localstorage is available.
- var storagetest = function (storage) {
- if (!! Storage) {
- try {
- Storage.setitem ("Key", "value");
- Storage.removeitem ("key");
- return true;
- catch (e) {
- return false;
- }
- }else{
- return false;
- }
- }
- Storagetest (Window.localstorage);
- Storagetest (Window.sessionstorage);