Safe Usage Of
HTML5 Storage

Safe Usage Of
HTML5 Storage

Celilsemi (Sam)
November 27th, 2016

Old cookie days, before HTML5 and its useful APIs like localStorage, developers were limited to cookies as storage on client-side scripting.

There were some advantages of cookies like being able to reach directly from some back-end solutions such as PHP and some disadvantages as well, such as storage size limitations, as low as 2mb per domain.

HTML5 lets developers move on with different technologies and different capabilities. One of the biggest evolutions happening around HTML5 today is browser-based persistent storage solution called “localStorage”.

Unlike cookies, the storage limit is far larger (at least 5MB) and the information is never transferred to the server.

It also comes with a high degree of uncertainty, because it is browser-based space and support can vary on different devices and browsers.

Being sure what is possible before using these new APIs is the most important thing before full integration.

How to measure HTML5 localStorage

First of all, checking the localStorage support is fairly simple; if the browser recognises the storage object as a function instead of undefined, it works.


if (typeof(Storage) !== "undefined") {
// According to caniuse.com 94 percent of all browsers fall into here.
// http://caniuse.com/#search=localStorage
} else {
// Sorry! No Web Storage support..
}

Hence, it seems like there isn’t much to worry about since almost all the browsers support localStorage.

Yet storage space browsers give, still varies and needs to be checked before usage to be error free.

Testing the capabilities is a bit more complex than this.


var b = 64; // testing block size
var i = 0;
var size = 0;
try {
// Test up to 50 MB
for (i = 0; i <= (1024*50); i += b) {
localStorage.setItem('test', new Array((i * 1024) + 1).join('d'));
}
} catch (e) {
localStorage.removeItem('test');
size = i ? i - b : 0;
}

This code snippet can return max storage left with a block size error rate.

The basic logic behind it is writing arbitrary data till the browser returns an error. As a result, code falls into catch and saves the last successfully stored size.
In conclusion, until HTML5 standards are sharp as a knife and default capabilities are certain to use, it is always better to test before use.

DigiGround generates future-proof web applications via testing and analysing the browser capabilities before delivering the projects so you can be sure to get a trouble free web solution.

Categories

Summary
Safe Usage of HTML5 Storage
Article Name
Safe Usage of HTML5 Storage
Description
The advantage and disadvantages of localStorage including how to measure HTML5 localStorage, in an easy to understand blog.
Author
Publisher Name
DigiGround
Publisher Logo