Source: kirupa.com

Today I would like to tell you a short guide about localStorage variable that is part of HTML5 and that can be used in your web development process. There are times when you might be in need of having a variable that is shared across different tabs or windows of your browser for the same domain, and this is not possible by simply declaring a JavaScript variable.

Let’s say for example that you want to grab the attention of the user of your application when he is currently not active in your application. You have declared a variable that will be used for counting the seconds that will get its value updated based on the activity of the user. If the user is typing something in the keyboard, or moving the mouse, then you reset the value of that variable to a proper initial value. If he is not using it, then you increase the value of that variable up to a fixed upper boundary that you use as an upper limit. If that limit is reached, then you might display a reminder for the user that he is idle. If he does not respond to that pop up by confirming that he is not idle, an Ajax call might be made to the server to expire the current session and the user will automatically get signed out.

Here comes the point at which this global variable is beneficial. The above mentioned scenario is one example of a plausible shortfall of that particular solution, as it might not consider the possibility of the usage of this application by that user from another tab or window. That variable that has the value of the seconds that have passed since the last key press or mouse move of the user has the scope of only the activity that has been done inside that tab or window. Thus, it does not cover the cases when the user has been using the same application, but from another tab or window of that browser.

However, you can solve this problem with localStorage variable.

For example, we can set an attribute associated to this variable such as, localStorage.setItem(“idleTime”, 0), where 0 is a String.

We can then update its value with a JavaScript function based on the activity of the user. If the user has not used the application for a certain period of time, then we can increase the value of idleTime attribute:

var currentIdleTimeString = localStorage.getItem(“idleTime);

var currentIdleTime = parseInt(currentIdleTimeString);

localStorage.setItem(“idleTime”, currentIdleTime + 1);

LocalStorage’s value will be shared across all the tabs and windows of the browser. It is better than cookies, because its limit is far larger (at least 5MB) and information is never transferred to the server. For more information about localStorage, you can read from W3Schools guide.