Thuộc tính sessionStorage của Cửa sổ HTML cho phép chúng tôi lưu trữ dữ liệu cặp khóa / giá trị trong trình duyệt web chỉ trong một phiên, nghĩa là dữ liệu sẽ bị xóa khi đóng tab trình duyệt.
Cú pháp
Sau đây là cú pháp -
window.sessionStorage
Hãy để chúng tôi xem một ví dụ về Thuộc tính sessionStorage của HTML Window -
Ví dụ
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background-color: #8BC6EC;
background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat;
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 30%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
.show{
font-size:1.2rem;
}
</style>
<body>
<h1>HTML Window sessionStorage Property Demo</h1>
<button onclick="store()" class="btn">Store 'John Smith' Name to sessionStorage</button>
<button onclick="display()" class="btn">Display sessionStorage stored value</button>
<div class="show"></div>
<script>
function store(){
sessionStorage.setItem('firstName','John');
sessionStorage.setItem('lastName','Smith');
document.querySelector('.show').innerHTML='Name store successfully';
}
function display(){
var firstName=sessionStorage.getItem('firstName');
var lastName=sessionStorage.getItem('lastName');
document.querySelector('.show').innerHTML='Name stored in sessionStorage is: '+ firstName +' '+lastName;
}
</script>
</body>
</html> Đầu ra
Nhấp vào “ Cửa hàng‘ John Smith Nút 'Name to sessionStorage "để lưu trữ tên cho sessionStorage:
Bây giờ hãy nhấp vào “ Hiển thị giá trị được lưu trữ của sessionStorage ”Để hiển thị giá trị được lưu trữ -
Giờ đây, bạn cũng có thể mở bộ nhớ phiên trong các công cụ dành cho nhà phát triển của mình để hiểu cách hoạt động của nó -