What is sessionStorage?
sessionStorage
is an object for the current session much like the localStorage
, sessionStorage can also store data in the memory of the browser, but this data cannot persist over multiple sessions, it gets deleted after a page session is ended.
- Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab.
- A page session lasts as long as the tab or the browser is open, and survives over page reloads and restores.
- Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
- Opening multiple tabs/windows with the same URL creates
sessionStorage
for each tab/window. - Closing a tab/window ends the session and clears objects in
sessionStorage
.
Data stored in the session storage is specific to the protocol of the page.
Syntax
myStorage = window.sessionStorage;
Modern browsers supporting local storage are
- Google Chrome ver 4.0 and above
- Microsoft Edge ver 8.0 and above
- Firefox ver 3.5 and above
- Apple Safari ver 4.0 and above
- Opera ver 11.5 and above
Web Storage API
The Web Storage API is a set of mechanisms that enable browsers to store key/value pairs. It is designed to be much more intuitive than using cookies.
The key/value pairs represent storage objects, which are similar to objects except they remain intact during page loads, and are always strings. You can access these values like an object or using the getItem()
method.
The Web Storage API consists of two mechanisms: sessionStorage
and localStorage
. Both sessionStorage
and localStorage
maintain a separate storage area for each available origin for the duration of the page session.
Methods in session storage
When the data gets updated in sessionStorage
, storage event triggers, with properties:
key
– the key that was changed (null
if.clear()
is called).oldValue
– the old value (null
if the key is newly added).newValue
– the new value (null
if the key is removed).url
– the url of the document where the update happened.storageArea
– eitherlocalStorage
orsessionStorage
object where the update happened.
The important thing is: the event triggers on all window
objects where the storage is accessible, except the one that caused it.
Syntax
window.sessionStorage
Syntax for SAVING data to sessionStorage:
sessionStorage.setItem("key", "value");
Syntax for READING data from sessionStorage:
var lastname = sessionStorage.getItem("key");
Syntax for REMOVING saved data from sessionStorage:
sessionStorage.removeItem("key");
Syntax for REMOVING ALL saved data from sessionStorage:
sessionStorage.clear();
Return type
Return Value: | A Storage object |
---|