Search code examples
javascripthtmllocal-storagesessionstorage

Scope of sessionStorage and localStorage


I read some documentation on sessionStorage and localStorage, but I don't understand what the scope is: the domain, a specific page?

For example, if I have the following pages:

http://example.com/products.aspx?productID=1

http://example.com/products.aspx?productID=2

http://example.com/services.aspx?serviceID=3

And if on each of the above pages I run (with idvalue being the value in the querystring):

localStorage.setItem('ID',idvalue);

Am I going to end up with 3 different values stored, or are the values going to overwrite each other?


Solution

  • The values are going to overwrite each other. Each key-name pair is unique for a protocol and domain, regardless of the paths.

    The affected domain can be changed via the document.domain property.

    • sub.example.com -> example.com is possible (subdomain)
    • sub.example.com -> other.example.com is not possible

    References:

    • MDN: Web Storage API: "sessionStorage maintains a separate storage area for each given origin [...]"
    • MDN: Origin: "Two objects have the same origin only when the scheme, hostname, and port all match."