LocalStorage 是用于在用戶瀏覽器中持久存儲(chǔ)字符串?dāng)?shù)據(jù)的 API,適用于保存用戶偏好、表單數(shù)據(jù)等非敏感信息。1. 它屬于 Web Storage API,數(shù)據(jù)不會(huì)隨瀏覽器關(guān)閉而消失;2. 僅支持字符串存儲(chǔ),需用 JSON.stringify() 和 JSON.parse() 轉(zhuǎn)換對(duì)象或數(shù)組;3. 提供 setItem、getItem、removeItem、clear 等同步方法;4. 不適合存儲(chǔ)敏感數(shù)據(jù)或大量數(shù)據(jù),存在 XSS 和容量限制風(fēng)險(xiǎn);5. 可通過(guò) storage 事件監(jiān)聽(tīng)跨標(biāo)簽頁(yè)更新。正確使用 LocalStorage 能提升用戶體驗(yàn),但需注意其局限與最佳實(shí)踐。
Local storage in JavaScript is one of those tools that seems simple at first glance but ends up being super useful once you get the hang of it. It lets you store data right in the user's browser, and unlike cookies, this data sticks around even after the browser closes. If you're building a web app or just want to remember something between visits—like a username, theme preference, or form input—localStorage is your friend.

Here’s how to think about localStorage and use it effectively without getting tripped up.

What Exactly Is localStorage?
LocalStorage is part of the Web Storage API, which gives websites the ability to store small bits of data locally in the user’s browser. Each domain gets its own separate storage space, so site A can't access site B's data.
- It's persistent – meaning it doesn’t go away when the browser closes.
- It stores strings only – if you want to save numbers, arrays, or objects, you’ll need to convert them into JSON strings first.
- It's synchronous – no waiting for a response like with more complex APIs.
You can imagine it like a little notebook the browser keeps for each website. Every time the page loads, it checks the notebook and uses whatever was written last time.

How to Use localStorage: Basic Methods
There are just a few core methods you need to know:
-
setItem(key, value)
– saves a key-value pair -
getItem(key)
– retrieves the value for a key -
removeItem(key)
– deletes a specific key -
clear()
– removes all stored data for the current domain -
key(index)
– gets the name of a key by index (useful for looping)
Let’s say you want to store a username:
localStorage.setItem('username', 'johndoe');
Later, you can retrieve it like this:
const user = localStorage.getItem('username'); console.log(user); // "johndoe"
If you try to store an object directly, like this:
localStorage.setItem('user', { name: 'John', age: 30 });
You’ll end up storing [object Object]
because setItem
expects a string. To fix that, you need to serialize the object:
localStorage.setItem('user', JSON.stringify({ name: 'John', age: 30 }));
And then parse it back when retrieving:
const userData = JSON.parse(localStorage.getItem('user')); console.log(userData.name); // "John"
This conversion step is easy to forget, especially when you’re new, but it’s essential.
When Should You Actually Use It?
LocalStorage is great for lightweight persistence. Here are a few real-world cases where it shines:
- User preferences: Save dark mode settings, language selection, or layout choices.
- Form recovery: Store partially filled forms so users don’t lose their progress if they accidentally refresh or close the tab.
- Offline caching: Temporarily keep data from an API call so the app still works if the network drops out briefly.
But be careful not to overdo it. Don’t store sensitive info like passwords or tokens here—it’s accessible via JavaScript, so it’s vulnerable to XSS attacks.
Also, localStorage has size limits (usually around 5–10MB per domain), so it's not suitable for large datasets.
Common Pitfalls and Tips
Here are a few gotchas that trip people up:
? No built-in expiration – Unlike cookies, localStorage never expires on its own. If you need something to expire after a while, consider using
sessionStorage
(which clears on tab close) or manually add a timestamp and check it before reading.? Data types matter – As mentioned earlier, everything is stored as a string. Always remember to
JSON.stringify()
before saving andJSON.parse()
when reading back.? Watch for updates across tabs – Changes to localStorage in one tab won’t trigger a UI update automatically in another tab unless you're listening for the
storage
event.
window.addEventListener('storage', (event) => { if (event.key === 'theme') { applyTheme(event.newValue); } });
This is helpful for apps that might open in multiple tabs and need to stay in sync.
- ? Keep it lean – Only store what’s necessary. Storing too much or too often can affect performance, especially on mobile devices.
LocalStorage isn’t magic, but it’s powerful enough for most basic client-side storage needs. Once you understand how it works and avoid the common traps, it becomes a solid tool in your JS toolkit.
That’s basically it — nothing too fancy, but really handy once you know how to use it right.
以上是JS綜述,用于理解和使用Web API,例如LocalStorage的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

FlaskvsFastAPI:高效開(kāi)發(fā)WebAPI的最佳選擇引言:在現(xiàn)代的軟件開(kāi)發(fā)中,WebAPI已經(jīng)成為了不可或缺的一部分。它們能夠提供數(shù)據(jù)和服務(wù),使得不同的應(yīng)用程序之間能夠進(jìn)行通信和互操作。而在選擇開(kāi)發(fā)WebAPI的框架時(shí),F(xiàn)lask和FastAPI是兩個(gè)備受關(guān)注的選擇。這兩個(gè)框架都非常流行,而且各有優(yōu)勢(shì)。在本文中,我們將對(duì)Fl

如何利用PHP后端功能開(kāi)發(fā)實(shí)現(xiàn)WebAPI?隨著互聯(lián)網(wǎng)的發(fā)展,WebAPI的重要性越來(lái)越被人們所認(rèn)識(shí)和重視。WebAPI是一種應(yīng)用程序編程接口,用于允許不同的軟件應(yīng)用之間進(jìn)行信息交換和互操作。PHP作為一種廣泛應(yīng)用于Web開(kāi)發(fā)的后端語(yǔ)言,也可以很好地用于開(kāi)發(fā)和實(shí)現(xiàn)WebAPI。本文將介紹如何使用PHP后端功能來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的WebAPI,并給出相關(guān)

隨著互聯(lián)網(wǎng)時(shí)代的發(fā)展,WebAPI已經(jīng)成為了互聯(lián)網(wǎng)應(yīng)用開(kāi)發(fā)的重要組成部分。Python語(yǔ)言作為一種高效、可讀性強(qiáng)的編程語(yǔ)言,也在WebAPI開(kāi)發(fā)中扮演著重要角色。本文將介紹使用Python編寫(xiě)WebAPI的最佳實(shí)踐,幫助開(kāi)發(fā)者更好地理解WebAPI的設(shè)計(jì)思路和開(kāi)發(fā)方式。一、設(shè)計(jì)RESTfulAPI在設(shè)計(jì)WebAPI時(shí),RESTfulAPI是最常

在 Web API 中,有非常有用的對(duì)象、屬性和函數(shù)可用于執(zhí)行小到訪問(wèn) DOM 這樣的小任務(wù),大到處理音頻、視頻這樣的復(fù)雜任務(wù)。常見(jiàn)的 API 有 Canvas、Web Worker、History、Fetch 等。下面就來(lái)看一些不常見(jiàn)但很實(shí)用的 Web API!

Golang中的WebAPI測(cè)試指南WebAPI測(cè)試是開(kāi)發(fā)過(guò)程中非常重要的一部分,它可以幫助我們檢測(cè)和驗(yàn)證API的功能和性能。在Golang中,有一些強(qiáng)大的庫(kù)和工具可以幫助我們進(jìn)行WebAPI測(cè)試。本文將為您介紹一些Golang中的WebAPI測(cè)試的基本原則和示例代碼。一、選擇適合的測(cè)試框架在Golang中,有多種測(cè)試框架可供選擇,如GoConvey

WebAPIvs.傳統(tǒng)API:比較不同類型的接口設(shè)計(jì)與應(yīng)用場(chǎng)景引言:在軟件開(kāi)發(fā)中,應(yīng)用程序接口(API)在不同的應(yīng)用場(chǎng)景中扮演著重要的角色。隨著Web應(yīng)用的興起,WebAPI作為一種新型的接口設(shè)計(jì)方式,與傳統(tǒng)API相比有著許多顯著的區(qū)別。本文將比較WebAPI和傳統(tǒng)API的不同之處,并通過(guò)具體的代碼示例來(lái)展示它們?cè)诓煌膽?yīng)用場(chǎng)景中的應(yīng)用。一、接口

隨著互聯(lián)網(wǎng)技術(shù)的不斷發(fā)展,WebAPI成為了現(xiàn)代應(yīng)用程序的核心構(gòu)建塊。WebAPI的快速、高效以及可擴(kuò)展性對(duì)于現(xiàn)今互聯(lián)網(wǎng)世界來(lái)說(shuō)是至關(guān)重要的。為了實(shí)現(xiàn)這些目標(biāo),Go語(yǔ)言作為一種快速、高效、并發(fā)的編程語(yǔ)言,已經(jīng)成為了眾多Web開(kāi)發(fā)人員的首選。在本文中,我們將介紹如何使用Gin框架來(lái)構(gòu)建高效的WebAPI,同時(shí)也會(huì)講述Gin框架的基本原理和開(kāi)發(fā)技巧

Go語(yǔ)言作為一種高效、可靠和易用的編程語(yǔ)言,被廣泛應(yīng)用于Web開(kāi)發(fā)領(lǐng)域,尤其是開(kāi)發(fā)WebAPI。在開(kāi)發(fā)一個(gè)WebAPI時(shí),使用Go語(yǔ)言可以提供許多最佳實(shí)踐,以確保代碼的可讀性、可測(cè)試性和可維護(hù)性。本文將討論Go語(yǔ)言開(kāi)發(fā)WebAPI的一些最佳實(shí)踐。第一條最佳實(shí)踐是使用標(biāo)準(zhǔn)庫(kù)。Go語(yǔ)言的標(biāo)準(zhǔn)庫(kù)提供了許多功能強(qiáng)大且易用的包,可以幫助我們快速構(gòu)建WebAPI
