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
sessionStoragefor each tab/window. - Closing a tab/window ends the session and clears objects in
sessionStorage.
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 thegetItem() 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 insessionStorage, storage event triggers, with properties:
key– the key that was changed (nullif.clear()is called).oldValue– the old value (nullif the key is newly added).newValue– the new value (nullif the key is removed).url– the url of the document where the update happened.storageArea– eitherlocalStorageorsessionStorageobject where the update happened.
window objects where the storage is accessible, except the one that caused it.
Syntax
window.sessionStoragesessionStorage.setItem("key", "value");var lastname = sessionStorage.getItem("key");sessionStorage.removeItem("key");sessionStorage.clear();Return type
| Return Value: | A Storage object |
|---|