Javascript write to session

How and When to Apply Session Storage with JavaScript

Session storage is a popular choice when it comes to storing data on a browser. It enables developers to save and retrieve different values. Unlike local storage, session storage only keeps data for a particular session. The data is cleared once the user closes the browser window.

Introduction

Session storage is a perfect alternative to cookies. Its syntax is quite straightforward. Beginners can easily learn and implement this storage. Session storage can also accommodate a huge amount of data. Most browsers, including Chrome and Firefox, can store about 10 MBs of data in session storage.

Prerequisites

To follow along, you must have some basic understanding of HTML and JavaScript. You should also have a browser installed on your computer.

Goal

To demonstrate how to store, retrieve, delete, and clear items in session storage.

Step 1 – Creating the project

First, create a new folder on your desktop. In this folder, create index.html and main.js files. You can then open these files in Visual Studio Code or your preferred editor.

All our JavaScript functions relating to the sessionStorage object will be in the main.js file. We will then import this file in the index.html .

Step 2 – Understanding session storage functions

Before we get started, it is important to understand the different methods supported by session storage. You will realize that session storage and localStorage have similar methods.

These being: setItem() , getItem() , removeItem() , and clear() .

setItem()

This method is called to store values in session storage. This method takes in the key and values as parameters.

sessionStorage.setItem("name:, "John Smith");; 

In the above function, name is the key, while John Smith is the value.

getItem()

This function is used to retrieve values from the session storage. It takes in the key as a parameter. Using the example above, the key is name .

var user = sessionStorage.getItem("name"); 

removeItem()

This method also requires a key as a parameter. The method will then delete the specified item from session storage.

When called, the above statement will remove John Smith from session storage.

clear()

As the name suggests, this function deletes all items from the session storage. This method does not require any parameters.

Let’s implement session storage in a real-life application.

Step 3 – Creating the view

In this step, we will design a simple web page that we will use to interact with the session storage functionalities. The page was designed using HTML5. The main.js file must be imported in the index.html file.

This allows us to access the required session storage functions. Kindly, note that we will use Bootstrap to style our web page. Here is the Bootstrap link.

link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> 

We import the main.js file using the code snippet below.

 script type="text/javascript" src="main.js">script> 

It’s important to ensure that all of our buttons have an id . This is because we will handle their click events in the main.js file.

 html>  head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>sessionStoragetitle>  script type="text/javascript" src="main.js">script>  link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">  head>  body>  div class="container" id="formDiv">  form class="form-signin" id="carForm">  h1>Enter detailsh1>  label for="carBrand" class="sr-only">Carlabel>  input type="text" id="carBrand" class="form-control" placeholder="Car brand" required autofocus>br>  label for="carPrice" class="sr-only">Pricelabel>  input type="text" id="carPrice" class="form-control" placeholder="Price" required>br>  button class="btn btn-lg btn-primary btn-block" type="submit">Submitbutton>  form>   button class="btn btn-lg btn-primary btn-block" id="retrieveButton">Retrieve recordsbutton>  div id="retrieve">div>   button class="btn btn-lg btn-danger btn-block" id="removeButton">Remove recordbutton>  button class="btn btn-lg btn-danger btn-block" id="clearButton">Clear all recordsbutton>  div>  body>  html> 

The above web page has four buttons with the ids of removeButton , clearButton , retrieveButton , and submit .

Читайте также:  Reading utf 8 xml in java

removeButton – When clicked, this button will call the removeItem function in the main.js file.

clearButton – This button calls the clearStorage method.

submit – Stores or saves values in sessionStorage .

clearButton – Deletes all items in sessionStorage .

All of these functions are defined in main.js file.

The store() will take in the user input and pass the values to the setItem() method as parameters. As a result, these values or objects will be stored in session storage. The code for the store() method is included below.

function store()< //stores items in sessionStorage  var brand = document.getElementById('carBrand').value;  var price = document.getElementById('carPrice').value;   const car =   brand: brand,  price: price,  >   window.sessionStorage.setItem('car',JSON.stringify(car));  //converting object to string  > 

The main.js also has a retrieveRecords() function to fetch the items in the sessionStorage . This function is outlined below. As noted, the getItem() requires a key to retrieve a specific object or value.

function retrieveRecords()< //retrieves items in sessionStorage  console.log("retrive records");  var records = window.sessionStorage.getItem('car');  var paragraph = document.createElement("p");  var infor = document.createTextNode(records);  paragraph.appendChild(infor);  var element = document.getElementById("retrieve");  element.appendChild(paragraph); > 

Just like the getItem() , the removeItem() method requires a key. In this example, the key is the car .

function removeItem()//deletes item from sessionStorage  sessionStorage.removeItem('car');  console.log("remove items"); > 

The clearStorage function will delete all items in the session storage when called.

Here is the required code snippet:

function clearStorage()< //clears the entire sessionStorage  sessionStorage.clear();  console.log("clear records"); > 

Here is the entire code in the main.js file:

 function store() < //stores items in the sessionStorage  var brand = document.getElementById('carBrand').value;  var price = document.getElementById('carPrice').value;   const car =   brand: brand,  price: price,  >   window.sessionStorage.setItem('car',JSON.stringify(car));  //converting object to string  >  function retrieveRecords() < //retrieves items in the sessionStorage  console.log("retrive records");  var records = window.sessionStorage.getItem('car');  var paragraph = document.createElement("p");  var infor = document.createTextNode(records);  paragraph.appendChild(infor);  var element = document.getElementById("retrieve");  element.appendChild(paragraph); >  function removeItem() //deletes item from sessionStorage  sessionStorage.removeItem('car');  console.log("remove items"); >  function clearStorage() < //clears the entire sessionStorage  sessionStorage.clear();  console.log("clear records"); >  window.onload =function() < //ensures the page is loaded before functions are executed.  document.getElementById("carForm").onsubmit = store;  document.getElementById("clearButton").onclick = clearStorage;  document.getElementById("removeButton").onclick = removeItem;  document.getElementById("retrieveButton").onclick = retrieveRecords; > 

You can follow the code below to store a list in session storage:

 function store() < //stores items in the local storage  var brand = document.getElementById('carBrand').value; //retrieves value  var price = document.getElementById('carPrice').value; //retrieve value   const car = brand: brand,price: price>   var vehicles = [car]; // adding an object to list  window.sessionStorage.setItem('car',JSON.stringify(vehicles));  //converting the list to string. SessionStorage only stores values in Strings  > 

Results

Note that the item that has been stored in session storage is the car object used in this tutorial. You can follow the video below to test the web page.

When to use session storage

Session storage can be used to check for the user’s authentication state. Users who are logged in can be redirected to the homepage. Unregistered users, on the other hand, are directed to the authentication page.

Session storage also helps prevent certain actions. For instance, it helps bar some users from making certain purchases. Developers can also use session storage to improve data safety. Once the user closes the browser tab, all their data is cleared. This makes it difficult for third parties to gain access.

Conclusion

By now, you should have a better understanding of session storage. You should consider using session storage as an alternative to cookies. Since it can offer great flexibility to developers.

Peer Review Contributions by: Lalithnarayan C

Источник

JavaScript Set Session Variable

JavaScript Set Session Variable

  1. localStorage vs sessionStorage in JavaScript
  2. Set Variable in localStorage and sessionStorage Using JavaScript

Our motive is to learn about sessions and set session variables in JavaScript. A session is a part of server-side storage where the data is stored and accessed depending on the unique id of each user.

For instance, whenever the user interacts with the website, it creates a new session object for that particular user and assigns them a cookie.

This cookie is checked whenever the user request from the exact client again and sent to the server for further processing and updating the session information that is already stored. The sessions get cleared as soon as the user clears the cookies.

You may have a question why is it important to use sessions?

The stateless HTTP protocol does not track any information about responses & requests, which means there is no relation among multiple requests by the one user (same user). The sessions are used to solve this issue.

For example, we have a form with multiple pages. Page 1, Page 2, and Page 3 are about personal information, education details, and family information, respectively.

The application can only be submitted once the user fills all three pages. In this scenario, we may need to store the submitted data from Page 1&2 into a session.

Once the user submits Page 3, we can get that page 3 from the HTTP request and the remaining Page 1&2 from the session. It is how sessions are used.

Now we understand sessions and know that the server maintains them. It is impossible to assign session values directly using JavaScript, but we (as web developers) want to use session storage locally to save, retrieve, update data.

We can use localStorage and sessionStorage .

localStorage vs sessionStorage in JavaScript

The localStorage object allows storing data in key-value pairs in the browser with no expiration. Even after closing the tab or browser, the data can be used for upcoming sessions (future sessions).

The sessionStorage object is similar to localStorage , but it stores data only for one session. The data is lost when the tab/browser is closed or refreshed.

Set Variable in localStorage and sessionStorage Using JavaScript

The methods are the same for storing and retrieving data in localStorage and sessionStorage . These methods are listed below.

  1. setItem(key, value) stores key-value pairs.
  2. getItem(key) retrieves the value via key.
  3. removeItem(key) removes both the key and value.
  4. clear() deletes the entire storage and clears everything.
  5. key(index) returns the key on a particular position.
  6. length tells the number of stored items.

Never use these storage mechanisms to store confidential information.

JavaScript Code to Practice For localStorage :

localStorage.setItem('fname','Bob'); localStorage.setItem('lname','Thomas');  console.log(localStorage.getItem('fname')); console.log(localStorage.getItem('lname'));  //returns null  console.log(localStorage.getItem('firstname'));  //removes the item with key and value  localStorage.removeItem('fname'); //clears the entire storage  localStorage.clear() 

JavaScript Code to Practice For sessionStorage :

sessionStorage.setItem('fname','Bob'); sessionStorage.setItem('lname','Thomas');  console.log(sessionStorage.getItem('fname')); console.log(sessionStorage.getItem('lname'));  //returns null  console.log(sessionStorage.getItem('firstname'));  //removes the item with key and value  sessionStorage.removeItem('fname'); //clears the entire storage  sessionStorage.clear() 

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article — JavaScript Variable

Источник

Оцените статью