Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

HTML5 Local Storage using Web Storage API

Before HTML5, application data had to be stored in cookies. Cookies can be used for persistent local storage of small amounts of data and they have the following drawbacks.

  • Cookies are included with every HTTP request, thereby slowing down your web application by needlessly transmitting the same data over and over
  • Cookies are included with every HTTP request, thereby sending data unencrypted over the internet (unless your entire web application is served over SSL)
  • Cookies are limited to about 4 KB of data - enough to slow down your application, but not enough to be terribly useful

With HTML5 Local Storage, web applications can store data locally within the user's browser. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Storage API can store key/value pairs, in a much more intuitive fashion than using cookies. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML Local Storage Objects

HTML local storage provides two objects for storing data on the client:

window.sessionStorage - maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, 
including page reloads and restores)
window.localStorage - does the same thing, but persists even when the browser is closed and reopened.

Invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved and removed.

Web Storage interfaces

Storage
Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
Window
The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage — which provide access to the current domain's 
session and local Storage objects respectively.
StorageEvent
The storage event is fired on a Document's Window object when a storage area changes.

Before using local storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! Your browser doesn't support local storage..
}

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

The following example creates a localStorage name/value pair with name="lastname" and value="gopi" and
retrieve the value of "lastname" and insert it into the element with id="result"

Example
// Store
localStorage.setItem("lastname", "gopi");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Note: Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a non-existent key will return null rather than throw an exception.

The example above could also be written like as:
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
Following are the methods for removing the value for a given named key, and clearing the entire storage area
localStorage.removeItem("lastname");
localStorage.clear();
Note: Calling removeItem() with a non-existent key will do nothing.

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

Example
if (localStorage.clickcount) {
    localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
    localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";


The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab. The following example counts the number of times a user has clicked a button, in the current session:

Example
if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";


Tracking Changes To The HTML5 STORAGE Area

If you want to keep track programmatically of when the storage area changes, you can trap the storage event. The storage event is fired on the window object whenever setItem(), removeItem(), or clear() is called and actually changes something. For example, if you set an item to its existing value or call clear() when there are no named keys, the storage event will not fire, because nothing actually changed in the storage area.

The storage event is supported everywhere the localStorage object is supported, which includes Internet Explorer 8. But IE 8 does not support the W3C standard addEventListener. Therefore, to hook the storage event, you’ll need to check which event mechanism the browser supports.
if (window.addEventListener) {
  window.addEventListener("storage", handle_storage, false);
} else {
  window.attachEvent("onstorage", handle_storage);
};
The handle_storage callback function will be called with a StorageEvent object, except in Internet Explorer where the event object is stored in window.event.
function handle_storage(e) {
  if (!e) { e = window.event; }
}
the variable e will be a StorageEvent object, which has the following useful properties

STORAGEEVENT Object

Property Type Description
key string he named key that was added, removed, or modified
oldValue any the previous value (now overwritten), or null if a new item was added
newValue any the new value, or null if an item was removed
url* string the page which called a method that triggered this change
*the url property was originally called uri. Some browser version follow uri instead of url. So you should check whether the url property exists, and if not, check for the uri property instead.

Note: The storage event is not cancelable. From within the handle_storage callback function, there is no way to stop the change from occurring. It’s simply a way for the browser to tell you, "Just Something happend".
“QUOTA_EXCEEDED_ERR” is the exception that will get thrown if you exceed your storage quota of 5 megabytes.

Browser Support

Following are the browser versions which supports Web Storage API
BrowserVersion
Chrome5.0+
IE8.0+
Firefox3.5+
Safari4.0+
Opera11.5+
You can check here for other browsers.

Check whether Browser tab is Active or Inactive using JQuery

In some situations we require to know whether our webpage is active or Inactive (i.e user works on other browser tab or another window) and need to perform some tasks based on the browser tab status. It is particularly useful for saving resources and not to perform unnecessary tasks when tab is not active. We can achive this using Page Visibility API ,it lets your application know when a page is visible to the user.

The current version of the Page Visibility API defines two document properties:
   1)  the boolean hidden and
   2)  the enumeration visibilityState.

     The visibilityState property currently has four possible values:
  • "hidden": the document is completely hidden from view
  • "visible": the document is at least partially visible on at least one display device
  • "prerender": the document is loaded off-screen and not visible (this value is optional; only some browsers supports it)
  • "unloaded": if the document is to be unloaded, then this value will be returned (this value is optional; only some browsers supports it)
The hidden attribute returns true when the document is not visible at all

Note: In Android Browser, these properties are vendor-prefixed, where you’ll need to use prefixed versions such as "webkitHidden" and "webkitVisibilityState". All other supporting browsers (IE 10+, Firefox, Chrome, Safari) implement the un-prefixed versions.

We can achieve this using simple JavaScript and jQuery both.

Using JQuery

$(document).ready(function () {
     $(window).focus(function(){
          document.title = 'Active';
     });
     $(window).blur(function(){
          document.title = 'Inactive';
     });
});


Using Javascript

Method 1: Using 'hidden' property

setInterval(function () { visibilitychange() }, 200);

visibilitychange = function () {

      var hidden;
      if (typeof document.hidden !== "undefined") {
             hidden = "hidden";
         }
     else if (typeof document.webkitHidden !== "undefined") {
             hidden = "webkitHidden";
          }
     else if (typeof document.mozHidden !== "undefined") {
               hidden = "mozHidden";
          }
     else if (typeof document.msHidden !== "undefined") {
                hidden = "msHidden";
           }

     if (document[hidden])
       document.title = "Inactive";
     else
        document.title = "Active";
 }


Method 2: Using 'visibilityState' property

 setInterval(function () { visibilitychange() }, 200);

 visibilitychange = function () {

    var BrowserState;
    if (typeof document.hidden !== "undefined") {
              BrowserState = "visibilityState";
         }
    else if (typeof document.webkitHidden !== "undefined") {
              BrowserState = "webkitVisibilityState";
         }
    else if (typeof document.mozHidden !== "undefined") {
              BrowserState = "mozVisibilityState";
         }
    else if (typeof document.msHidden !== "undefined") {
             BrowserState = "msVisibilityState";
         }

     if (document[BrowserState] == "hidden")
        document.title = "Inactive";
     else
        document.title = "Active";
  }


It is useful in the following situations

1) Play/Pause the video if webpage is not active.
2) An application can decide to display notifications to the user only when it is hidden from view
3) A website has an image carousel that shouldn’t move to the next slide if user are not viewing the page.