Just Learn Code

Exploring the Power of JavaScript SessionStorage for Web Development

Introduction to JavaScript sessionStorage

When browsing webpages, you might have heard about the term sessionStorage. But what does it actually mean, and how does it work?

SessionStorage is a JavaScript API that enables web developers to store data in the browser that is specific to the user’s session. This means that the data is available only during the user’s session, and when the session ends, the data is cleared.

In this article, we will explore what sessionStorage is, how it works, and how to manage data in it using methods such as setItem, getItem, removeItem, key, and clear.

Lifespan of a page session and its relation to sessionStorage

Before we dive into sessionStorage, let’s clarify what we mean by a session. A session refers to the time when a user is interacting with a website or webpage until they close the browser or end the activity.

When a user visits a website, their session starts. During this time, the website collects data related to the user’s actions and preferences, such as their name, address, or browsing history.

This data is stored in memory, and once the user terminates the session, the data is cleared. Now, let’s focus on sessionStorage.

In contrast to a session, sessionStorage is limited to a single browser window or tab. When a user opens multiple tabs or windows, each one has its own sessionStorage.

This means that data stored in one window or tab is not accessible in another. So, if you fill out a form in one tab and navigate to another, the form data will not carry over to the new tab.

Separate sessionStorage in multiple tabs or windows

As mentioned before, each browser tab or window has its own sessionStorage. This feature is useful when a user needs to perform various tasks that require different data sets.

For instance, a user can open multiple tabs to purchase items on different online stores. Each tab maintains its own shopping cart, billing, and shipping information, ensuring that data does not collide or mix up.

Data specificity and availability based on the protocol of the page

The sessionStorage API is based on a security concept called same-origin policy. This policy restricts the access of a webpage from a different origin.

An origin is a combination of a protocol (http or https), domain, and port. The same-origin policy aims to prevent unauthorized access of data from one webpage to another.

When it comes to sessionStorage, this means that data stored in sessionStorage is specific to the protocol of the webpage. If a user first visits a webpage over HTTPS, sessionStorage data will only be accessible while the user is on an HTTPS page.

If the user navigates to an HTTP page, the sessionStorage data will no longer be available.

Unavailability of sessionStorage when running pages locally without a server

One important thing to note about sessionStorage is that it is not available when running pages locally without a server. Browsers do not allow sessionStorage to be used locally as the same-origin policy does not apply to local files.

This means that developers need to run pages on a local server, such as Apache or Node.js, to use sessionStorage correctly.

Methods to manage data in sessionStorage

To manage data in sessionStorage, we can use five methods provided by the sessionStorage API: setItem, getItem, removeItem, key, and clear. Here is a brief explanation of each method:

– setItem: inserts a key-value pair into the sessionStorage.

– getItem: retrieves the value of a specific key from the sessionStorage. – removeItem: removes a key-value pair from the sessionStorage.

– key: returns the name of the key at a specific index in the sessionStorage. – clear: removes all key-value pairs from the sessionStorage.

Accessing the sessionStorage

To access the sessionStorage in JavaScript, we use the window object. The window object provides access to the browser’s session storage, and all the methods mentioned above can be used with it.

Here is an example code snippet:

// Store data in sessionStorage

sessionStorage.setItem(‘name’, ‘John’);

// Retrieve data from sessionStorage

let name = sessionStorage.getItem(‘name’);

// Remove data from sessionStorage

sessionStorage.removeItem(‘name’);

Conclusion

In this article, we explored what sessionStorage is, how it works, and how to manage data in it using the sessionStorage API’s methods. We also discussed the lifespan of a session and its relation to sessionStorage, as well as the limitations of sessionStorage, such as its unavailability when running pages locally without a server.

By understanding sessionStorage, you can improve the user experience by creating personalized and secure web applications.

Storing data in the sessionStorage

Storing data in sessionStorage is simple and can be done using name-value pairs. A name-value pair consists of a unique key and a corresponding value, and it can be used to store a wide range of data types, such as strings, numbers, objects, and arrays.

For instance, suppose you have a JavaScript object containing user data, such as name, email, and age. You can store this data in sessionStorage by creating a unique key for each value and assigning the corresponding value to the key.

Here is an example code snippet:

// Create a user object

const user = {

name: “John”,

email: “[email protected]”,

age: 25

};

// Store user object in sessionStorage

sessionStorage.setItem(‘user’, JSON.stringify(user));

The first line creates a JavaScript object called user, which contains the properties name, email, and age, and their respective values. The second line stores the user object in sessionStorage using the setItem method.

Updating and inserting items in storage using setItem method

One thing to keep in mind when using sessionStorage is that the setItem method overwrites the existing value of a key. If you want to update the value of a key without overwriting it, you need to retrieve the existing value, modify it, and then store it back using the setItem method.

For example, suppose you want to update the age of a user stored in sessionStorage. You can retrieve the user object using the getItem method, modify its age property, and then store the modified object back using the setItem method.

Here is an example code snippet:

// Retrieve user object from sessionStorage

const user = JSON.parse(sessionStorage.getItem(‘user’));

// Update the age property

user.age = 30;

// Store updated user object back in sessionStorage

sessionStorage.setItem(‘user’, JSON.stringify(user));

The first line retrieves the user object stored in sessionStorage using the getItem method and converts it from a JSON string back to a JavaScript object using the JSON.parse method. The second line updates the age property of the user object to 30.

The third line stores the updated user object back in sessionStorage using the setItem method.

Getting data from the sessionStorage

To retrieve data stored in sessionStorage, we use the getItem method. The getItem method takes a key as its parameter and returns the value associated with the key.

Here is an example code snippet:

// Retrieve name from sessionStorage

const name = sessionStorage.getItem(‘name’);

The code snippet retrieves the value associated with the key name from sessionStorage using the getItem method and stores it in a variable called name.

Conclusion

SessionStorage is a powerful JavaScript API that allows web developers to store data in the browser that is specific to the user’s session. Using the sessionStorage API, web developers can store and manage data in the browser memory, making it useful for a wide range of applications.

In this expansion, we covered storing data in sessionStorage using name-value pairs, updating and inserting items in storage using the setItem method, and retrieving data from sessionStorage using the getItem method. With this knowledge, you can implement sessionStorage to improve the user experience and create personalized and secure web applications.

Removing an item by name

In sessionStorage, deleting a specific item is possible using the removeItem method. This method takes a key as its parameter and removes the item associated with that key from the sessionStorage.

Here is an example code snippet:

// Remove item from sessionStorage

sessionStorage.removeItem(‘name’);

The code snippet removes the item associated with the key name from the sessionStorage using the removeItem method. It’s important to mention that if you try to remove an item that does not exist in the sessionStorage, no error will be thrown.

The removeItem method will simply do nothing and continue executing the rest of the code.

Iterating over all items

Sometimes, you may need to iterate over all the items stored in the sessionStorage. To achieve this, we can use the Object.keys() method to retrieve all the keys in the sessionStorage and then use a for…of loop to iterate over them.

Here are the steps to iterate over all items stored in sessionStorage:

1. Retrieve all keys in the sessionStorage using the Object.keys() method and store them in an array.

2. Iterate over the array of keys using a for…of loop.

3. Retrieve the value of each key using the getItem method and do something with it.

Here is an example code snippet that demonstrates these steps:

// Retrieve all keys from sessionStorage

const keys = Object.keys(sessionStorage);

// Iterate over all keys

for (const key of keys) {

// Retrieve value of each key

const value = sessionStorage.getItem(key);

// Do something with the value

console.log(`${key}: ${value}`);

}

The code snippet retrieves all the keys in the sessionStorage using the Object.keys() method and stores them in an array called keys. Then, it iterates over this array using a for…of loop, retrieving the value of each key using the getItem method, and finally doing something with the value.

It’s important to note that the order in which the keys are retrieved may not be the same as the order in which they were stored. This is because sessionStorage does not impose any ordering on the key-value pairs.

Conclusion

In this expansion, we covered two more topics related to sessionStorage. First, we learned how to remove an item by name using the removeItem method.

Second, we stepped through the process of iterating over all items stored in sessionStorage using the Object.keys() method and a for…of loop. These functionalities allow for more flexibility when working with sessionStorage and retrieving or manipulating data stored in it.

With this knowledge, developers can create even more powerful web applications that utilize the capabilities of sessionStorage.

Deleting all items in the sessionStorage

Occasionally, you may need to delete all items stored in the sessionStorage. This can be done using the clear() method, which deletes all key-value pairs stored in the sessionStorage.

Here is an example code snippet:

// Delete all items in sessionStorage

sessionStorage.clear();

The code snippet clears all key-value pairs stored in the sessionStorage using the clear() method. It’s important to note that once a browser tab or window is closed, all data stored in its corresponding sessionStorage is automatically deleted.

This is because sessionStorage is only available during the user’s session, which ends when the tab or window is closed.

JavaScript sessionStorage application

Now that we’ve covered the basics of sessionStorage, let’s explore some practical applications of using it to improve user experience. We’ll create a simple web application that uses sessionStorage to remember the user’s selected mode (light, dark, or default).

Building a simple web application using sessionStorage to remember user-selected mode

First, let’s create the project folder structure:

“`

– web-app

– index.html

– app.js

– style.css

“`

The index.html file contains the HTML markup for the web application, while the app.js file holds the JavaScript code that defines how the application behaves. Finally, the style.css file contains the styles that dictate how the application looks.

Next, let’s define the three modes:

“`javascript

const MODES = {

LIGHT: ‘light’,

DARK: ‘dark’,

DEFAULT: ‘default’

};

“`

We’ll use these modes to set the initial mode of the application and to toggle between the different modes. Now, let’s select the button that toggles the mode using the querySelector() method:

“`javascript

const modeButton = document.querySelector(‘.mode-button’);

“`

We’ll define a setMode() function to change the mode of the application:

“`javascript

function setMode(mode) {

document.body.classList.remove(MODES.LIGHT);

document.body.classList.remove(MODES.DARK);

sessionStorage.setItem(‘mode’, mode);

if (mode === MODES.LIGHT) {

document.body.classList.add(MODES.LIGHT);

} else if (mode === MODES.DARK) {

document.body.classList.add(MODES.DARK);

}

}

“`

The setMode() function removes any existing mode classes from the body element, sets the new mode in sessionStorage, and adds the appropriate mode class to the body element.

To toggle between light and dark modes, we’ll add a click event handler to the mode button:

“`javascript

modeButton.addEventListener(‘click’, () => {

const currentMode = sessionStorage.getItem(‘mode’) || MODES.DEFAULT;

if (currentMode === MODES.DEFAULT) {

setMode(MODES.LIGHT);

} else if (currentMode === MODES.LIGHT) {

setMode(MODES.DARK);

} else if (currentMode === MODES.DARK) {

setMode(MODES.DEFAULT);

}

});

“`

The click event handler retrieves the current mode from sessionStorage or sets it to the default mode if it hasn’t been set yet. Depending on the current mode, it toggles between light, dark, and default modes using the setMode() function.

Finally, to save the mode to sessionStorage, we’ll call the setMode() function with the initial mode:

“`javascript

const initialMode = sessionStorage.getItem(‘mode’) || MODES.DEFAULT;

setMode(initialMode);

“`

And that’s it! With this simple application, we’ve demonstrated how sessionStorage can be used to remember user preferences and make the web experience more personalized.

Viewing stored data in sessionStorage

To view the data stored in sessionStorage, you can use the developer tools in your browser. In Google Chrome, for example, you can open the developer tools by pressing F12 or Ctrl+Shift+I and then navigate to the Application tab.

In the Storage section, you can view the data stored in sessionStorage, including the keys and their corresponding values.

Conclusion

In this expansion, we covered two more topics related to sessionStorage. We learned how to delete all items in sessionStorage using the clear() method and how to create a simple web application that uses sessionStorage to remember the user’s selected mode.

Using sessionStorage, you can create personalized and responsive web applications that cater to each user’s unique preferences. With the knowledge gained in this article, you can start using sessionStorage to create powerful and dynamic web applications.

In summary, we explored the topic of JavaScript sessionStorage and how it can be used to store data in a browser-specific user session. We covered various aspects of sessionStorage, including its lifespan, data specificity, managing data, accessing data, and deleting data.

We also discussed its practical applications, including building a simple web application to remember user-selected mode, and viewing stored data in sessionStorage. Takeaways from this article include learning about the various methods provided by the sessionStorage API, using sessionStorage to create personalized web applications, and exploring the many functionalities of sessionStorage.

By understanding sessionStorage, web developers can create responsive, secure, and dynamic web applications that cater to each user’s unique preferences.

Popular Posts