Storage - Javascript

  • Local Storage
    • Theory
      • A web storage object which are not sent to server with each request
      • Keys and Values should be string
    • Commands
      • localStorage.setItem("key", "value")
        • localStorage.key=value
      • localStorage.getItem("key")
      • localStorage.removeItem("key")
        • delete localStorage.key
      • localStorage.clear()
      • localStorage.key(index)
      • localStorage.length
      • JSON.stringify(object) => Converts objects to JSON string
      • JSON.parse(string) => Converts string (must be a valid JSON) to objects
  • Session Storage
    • Theory
      • Exists only within current browser tab
      • Data survives page refresh but not opening/closing the tab
  • Cookies
    • Theory
      • Small string of data stored directly in the browser
      • Cookies are set by web server using the Set-Cookie HTTP-header, Next time when request is sent using same domain, browser sends the cookie with Cookie HTTP-header
    • Commands
      • document.cookie => Returns cookies delimited by semicolon
      • document.cookie="key=value" => Adds to the cookies instead of replacing as key value pair
        • value should not exceed 4 KB
        • Total number of cookies per domain is limited to around 20+
      • document.cookie="key=value;path=/a;expires=date" => Adds with options
      • encodeURIComponent(value) => Encode the value as a string
      • decodeURIComponent(value) => Decode the value as a string
  • Storage Event
    • When data gets updated in local or session storage, storage event triggers properties like key, old value, new value, url, storage area
    • Syntax
          window.onstorage = (e) => {
              console.log(e);
          }
      
Share: