1. Introduction
The Web Storage API offers a more user-friendly way for browsers to store key-value pairs, serving as an intuitive alternative to cookies.
2. Concepts and usage
The two mechanisms within Web Storage are as follows:
sessionStorage
: creates a unique storage area for each origin, accessible throughout the page session. This storage persists while the browser tab remains open, even across page reloads and restores, but is cleared when the tab is closed.localStorage
: UnlikesessionStorage
,localStorage
also provides a dedicated storage area for each origin but retains the data even after the browser is closed and reopened, ensuring persistence across sessions.
The Window.sessionStorage
and Window.localStorage
properties provide access to these storage mechanisms. Each property returns an instance of a Storage
object, allowing you to set, retrieve, and remove data items. A separate Storage
object is allocated for sessionStorage
and localStorage
for each origin, ensuring that they operate independently and are managed separately.
Both sessionStorage
and localStorage
in the Web Storage API operate synchronously. This means that any read, write, or delete operation on these storage mechanisms blocks the execution of other JavaScript code until the operation is complete. While straightforward, this synchronous nature can impact the performance of a web application, particularly when handling large volumes of data or performing frequent storage operations.
Asynchronous alternatives, such as IndexedDB, may be more suitable for scenarios where performance is a concern or when dealing with larger datasets.
3. Determining storage access by third party
Each origin maintains its own isolated storage for both web storage (localStorage
and sessionStorage
) and shared storage. However, a third-party script’s access to shared storage depends on the browsing context in which it is executed.
Third-party scripts can be included in a website either by:
- Injecting a
<script>
element: When added this way, the third-party code executes within the browsing context of the host (the embedder). Any calls toStorage.setItem()
orSharedStorage.set()
by the third-party script will write data to the host’s storage, as the browser treats the embedded script the same as first-party code. - Embedding within an
<iframe>
: When included in an<iframe>
, the third-party code executes within the<iframe>
‘s origin and browsing context. In this case:- Calls to
Storage.setItem()
write to the web storage (local or session) of the<iframe>
‘s origin. - Calls to
SharedStorage.set()
write to the shared storage of the<iframe>
‘s origin.
- Calls to
Thus, the way third-party code is integrated (via <script>
or <iframe>
) determines which storage it can access and modify.
4. Web Storage interfaces
Storage
: Allows you to set, retrieve and remove data for a specific domain and storage type (session or local).Window
: The Web Storage API extends the Window object with two new properties —Window.sessionStorage
andWindow.localStorage
— which provide access to the current domain’s session and local Storage objects respectively, and a storage event handler that fires when a storage area changes (e.g., a new item is stored).StorageEvent
: Thestorage
event is fired on a document’s Window object when a storage area changes.
5. Using the Web Storage API
Storage objects function as straightforward key-value stores, much like JavaScript objects, but their data persists across page reloads. Both keys and values are always stored as strings (integer keys are automatically converted to strings, similar to object behavior). You can interact with storage data either like a regular object or by using the Storage.getItem()
and Storage.setItem()
methods. For instance, the following three lines all set the same colorSetting
entry:
localStorage.colorSetting = "#a4509b"; localStorage["colorSetting"] = "#a4509b"; localStorage.setItem("colorSetting", "#a4509b");
Note: It’s recommended to use the Web Storage API (setItem
, getItem
, removeItem
, key
, length
) to prevent the pitfalls associated with using plain objects as key-value stores.
6. Feature-detecting localStorage
To be able to use localStorage
, we should first verify that it is supported and available in the current browsing session. This API is available in current versions of all major browsers. Testing for availability is necessary only if you must support very old browsers, or in the limited circumstances described below.
Browsers that support localStorage
have a property on the window object named localStorage
. However, just asserting that the property exists may throw exceptions. If the localStorage
object does exist, there is still no guarantee that the localStorage
API is actually available, as various browsers offer settings that disable localStorage
. So a browser may support localStorage
, but not make it available to the scripts on the page.
For example, for a document viewed in a browser’s private browsing mode, some browsers might give us an empty localStorage
object with a quota of zero, effectively making it unusable.
Here is a function that detects whether localStorage
is both supported and available:
function storageAvailable(type) { let storage; try { storage = window[type]; const x = "__storage_test__"; storage.setItem(x, x); storage.removeItem(x); return true; } catch (e) { return ( e instanceof DOMException && e.name === "QuotaExceededError" && // acknowledge QuotaExceededError only if there's something already stored storage && storage.length !== 0 ); } }
And here is how you would use it:
if (storageAvailable("localStorage")) { // Yippee! We can use localStorage awesomeness } else { // Too bad, no localStorage for us }
You can test for sessionStorage
instead by calling storageAvailable('sessionStorage')
.
7. Window: localStorage property
The localStorage
read-only property of the window
interface allows you to access a Storage
object for the Document
‘s origin; the stored data is saved across browser sessions.localStorage
is similar to sessionStorage
, except that while localStorage
data has no expiration time, sessionStorage
data gets cleared when the page session ends — that is, when the page is closed. (localStorage
data for a document loaded in a “private browsing” or “incognito” session is cleared when the last “private” tab is closed.)
The keys and the values stored with localStorage
are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.
localStorage
data is specific to the protocol of the document. In particular, for a site loaded over HTTP (e.g., http://example.com
), localStorage
returns a different object than localStorage
for the corresponding site loaded over HTTPS (e.g., https://example.com
).
7.1 Example
The following snippet accesses the current domain’s local Storage
object and adds a data item to it using Storage.setItem()
.
localStorage.setItem("myCat", "Tom");
The syntax for reading the localStorage
item is as follows:
const cat = localStorage.getItem("myCat");
The syntax for removing the localStorage
item is as follows:
localStorage.removeItem("myCat");
The syntax for removing all the localStorage
items is as follows:
localStorage.clear();
8. Window: sessionStorage property
The read-only sessionStorage
property accesses a session Storage
object for the current origin. sessionStorage
is similar to localStorage
; the difference is that while data in localStorage
doesn’t expire, data in sessionStorage
is cleared when the page session ends.
- 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. - Duplicating a tab copies the tab’s
sessionStorage
into the new tab. - Closing a tab/window ends the session and clears objects in
sessionStorage
.
Data stored in sessionStorage
is specific to the protocol of the page. In particular, data stored by a script on a site accessed with HTTP (e.g., http://example.com/
) is put in a different sessionStorage
object from the same site accessed with HTTPS (e.g., https://example.com/
).
The keys and the values are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.
8.1 Examples
// Save data to sessionStorage sessionStorage.setItem("key", "value"); // Get saved data from sessionStorage let data = sessionStorage.getItem("key"); // Remove saved data from sessionStorage sessionStorage.removeItem("key"); // Remove all saved data from sessionStorage sessionStorage.clear();