随笔 - 547  文章 - 213 评论 - 417 阅读 - 107万

 

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

It should be noted that data stored in either sessionStorage or localStorage is specific to the protocol of the page.

Syntax

// Save data to sessionStorage
					

sessionStorage.setItem('key',
											'value');
													

 

// Get saved data from sessionStorage
					

var data = sessionStorage.getItem('key');
													

 

// Remove saved data from sessionStorage
					

sessionStorage.removeItem('key');
										

 

// Remove all saved data from sessionStorage
					

sessionStorage.clear();
								

Value

Storage object.

Example

The following snippet accesses the current domain's session Storage object and adds a data item to it using Storage.setItem().

sessionStorage.setItem('myCat',
											'Tom');
													

The following example autosaves the contents of a text field, and if the browser is accidentally refreshed, restores the text field content so that no writing is lost.

// Get the text field that we're going to track
					

var field = document.getElementById("field");
													

 

// See if we have an autosave value
					

// (this will only happen if the page is accidentally refreshed)
					

if
						(sessionStorage.getItem("autosave"))
														{
															


					// Restore the contents of the text field
						

  field.value = sessionStorage.getItem("autosave");
														

}
					

 

// Listen for changes in the text field
					

field.addEventListener("change",
											function()
														{
															


					// And save the results into the session storage object
						

  sessionStorage.setItem("autosave", field.value);
														

});
					

Note: Please refer to the Using the Web Storage API article for a full example.

 

From: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

posted on   今夜太冷  阅读(1680)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2016-10-19 ActiveX: 如何用.inf和.ocx文件生成cab文件
点击右上角即可分享
微信分享提示