Scope of Sessionstorage and Localstorage

Scope of sessionStorage and localStorage

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

SessionStorage browser wide (scope) or LocalStorage deleted on exit

Finally I gave up of the server side sessions because it raised other issues, and solved it with this workflow:

  • After page load, localStorage value is set if it hasn't been before, as well as flag that the player is opened in this tab. If the localStorage is already set, flag is set to false.

  • If flag is set, play video, otherwise prohibit.

  • On page unload, only if the flag is set (that is, if user opened video in this tab), remove localStorage value.

$(function () {    if (localStorage.playerTabOpened) {        var dateNow = Date.now();        var diffSinceLastTabOpened = (dateNow - localStorage.playerTabOpened) / 1000;        // if playerTabOpened value was stored more than 1 day ago, delete it anyway because it could be left by chance        if (diffSinceLastTabOpened > 86400) {            localStorage.removeItem("playerTabOpened");        };    }    if (!localStorage.playerTabOpened) {        shared.playerTabOpenedHere = true;        localStorage.setItem("playerTabOpened", Date.now());    } else {        shared.playerTabOpenedHere = false;    }});
$(window).on("beforeunload", function () { if (shared.playerTabOpenedHere) { localStorage.removeItem("playerTabOpened"); }});
if (shared.playerTabOpenedHere) { // play} else { // throw error}

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

Example Data of localstorage and sessionstorage

1) The data you store either with LocalStorage or SessionStorage depends on how you want your user to experience your application.

For example, if you have a login page, the username should be something kept with LocalStorage, because probably this same user will log into your app multiple times and not necesseraly wants to save the password in the browser. Having the username in LocalStorage will make it easier for the user to login in the future, even after closing the browser or changing tabs.

But, if you have a system that provides services like booking, searching or maybe comparison between products, storing data with SessionStorage would be better, because although the values set by the user while using your application won't change during this session, they might - and probably will - change in a future use of your application.

In your case specifically, and repeating what was said in the beginning, even with changes in your list of countries, you need to have in mind how your user will interact with your system and what are your needs with the data that is being provided by them.

Don't forget you can always clean the localStorage if you need, and set new values as they appear.

2) There's a really good explanation of how the browser responds to a full memory here

In HTML5, is the localStorage object isolated per page/domain?

It's per domain and port (the same segregation rules as the same origin policy), to make it per-page you'd have to use a key based on the location, or some other approach.

You don't need a prefix, use one if you need it though. Also, yes, you can name them whatever you want.

$sessionStorage and how to view and work with $sessionStorage in AngularJs

$sessionStorage is an AngularJs service found at: https://github.com/gsklee/ngStorage

It allows you to read and write to $localStorage and $sessionStorage, making use of these stored parameters during the lifetime of your session.

You will not be able to view these $sessionStorage or $localStorage items via the dev tools, but you can view the values by assigning it to a variable in your code.

Example:

var whatIsInMyStorage = $localStorage; // or $sessionStorage; 

You can also clear these storage items by calling:

$sessionStorage.$reset();
$localStorage.$reset();

I hope this helps someone else.

sessionStorage proxy class scope

Some window objects like location are read-only, it can be useful to create abstractions over them or make use of DI for testability.

sessionStorage is supposed to be used as is. Usually no abstractions over it are needed. If its functionality should be extended or modified, a custom class can be created. It can implement Storage interface or have its own.

The use of Proxy is unjustified here. It is slow and restricts the code from being used in ES5 environments.

Custom class or object can just wrap original sessionStorage methods. Since Storage API is small, wrapper class results in ~20 lines of code:

class CustomSessionStorage {
get length() {
return sessionStorage.length;
}

getItem(key) {
return sessionStorage.getItem(key);
}
...
}

sessionStorage object is exotic. Although it inherits from Storage, Storage is not a constructor, and sessionStorage methods should be bound to sessionStorage directly, so it's not possible to make it work just with CustomSessionStorage.prototype = sessionStorage. Additionally, sessionStorage has length property descriptor that should be bound as well.

A more general way to extend it is to provide a base class that wraps original methods and can be extended further:

function BaseSessionStorage() {}

for (let prop of Object.getOwnPropertyNames(Storage.prototype)) {
if (typeof sessionStorage[prop] === 'function') {
// bind all sessionStorage methods
BaseSessionStorage.prototype[prop] = sessionStorage[prop].bind(sessionStorage);
} else {
// a proxy for other props, length is read-only getter
Object.defineProperty(BaseSessionStorage.prototype, prop, {
get: () => sessionStorage[prop],
set: val => { sessionStorage[prop] = val }
});
}
}

class CustomSessionStorage extends BaseSessionStorage {
getItem(key) {
return super.getItem(key);
}
// the rest of API is inherited
}


Related Topics



Leave a reply



Submit