Friday, April 19, 2013

How to use with Cookies in Javascript.


function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

 createCookie("username","rkumar670","30");
var val = readCookie("username");
output = rkumar670


eraseCookie('rkumar670');


Wednesday, April 10, 2013

LocalStorage


LocalStorage works mostly as you expect it; it’s a simple key-value-store with a finite amount of storage, and once you hit that you get an exception. But we got a really wierd bug report from a user where he would browse to another site, and come back to the application to find that all of his settings and data were gone.

Turns out that under some circumstances, Android doesn’t load the localStorage data when you hit the back button. I’m guessing it has something to do with the fact that Android doesn’t always reload the page when you go back, it loads it from the browser cache (not the application cache) instead.

So to get around this Android bug, we set a persistent value in localStorage which we use as a check to see if localStorage is correctly loaded.


var check = "1234567890"
localStorage.setItem("android_check", check);

and when we want to fetch something from localStorage, we do:

var hasItem = function() {
  return (typeof localStorage[key] != "undefined" && localStorage[key] !== null);
}


var getItem = function(key, def) {
  if (!hasItem(key)) {
    if (localStorage.getItem("android_check") !== check) {
      // Reload the page so Android reloads localStorage
      window.location.reload();
    }
    return def;
  }
  return localStorage.getItem(key);
}