Session is a way to store information related to the user's session on the server. When a user accesses a website (opens a new tab), the server creates a new Session and assigns a unique ID to it. This ID is sent to the user's browser and stored in a cookie or passed through URL parameters.
Session information is stored on the server and can be deleted when the session ends or expires.
Session has some important advantages when used in web applications:
To use Session in JavaScript, we can use the sessionStorage and sessionStorage methods. Here is an example of how to use Session to store user information:
// Lưu tên người dùng vào Session Storage
sessionStorage.setItem('username', 'John Doe');
// Lấy tên người dùng từ Session Storage
const username = sessionStorage.getItem('username');
console.log(username); // Output: John Doe
// Xóa tên người dùng khỏi Session Storage
sessionStorage.removeItem('username');
In the example above, we use the setItem() method to store the user's name in the Session Storage with the key 'username' and the value 'John Doe'. Then, we use the getItem() method to retrieve the user's name from the Session Storage and assign it to the variable username. Finally, we use the removeItem() method to delete the user's name from the Session Storage.