使用 Chrome Storage API
使用 `chrome.storage` API 安全高效地持久化用户设置和数据,并实现本地存储与同步存储
使用 Chrome Storage API 是 CoddyKit 上的免费 Browser Extensions Development (Chrome & Edge) 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Browser Extensions Development (Chrome & Edge) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Browser Extensions Development (Chrome & Edge) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Intro to Chrome Storage API
When building browser extensions, you often need to save data. This could be user settings, application state, or cached information.
The chrome.storage API provides a way to store data persistently, meaning it stays even after the browser closes or the extension is updated.
Why Use chrome.storage?
Unlike regular JavaScript variables, data stored with chrome.storage is persistent. Here's why it's a great choice for extensions:
- Persistence: Data remains after the browser closes and across updates.
- Security: It's isolated to your extension, preventing conflicts with other extensions or web pages.
- Asynchronous: Operations don't block the main thread, keeping your extension responsive.
- Key-Value Store: Easy to store and retrieve data as simple key-value pairs.
Local Storage: chrome.storage.local
The chrome.storage.local area is designed for storing data that should only be available on the current browser profile.
It's ideal for things like temporary user preferences, cached content, or data specific to one browser instance. The storage limit is typically 5MB.
Sync Storage: chrome.storage.sync
For data that users might want to access across different browsers or devices (if they are logged into their Google account), chrome.storage.sync is the solution.
It automatically syncs data across all instances where the user has your extension installed and is logged in. The storage limit is smaller, typically 100KB, with a maximum of 8KB per item.
storage vs. localStorage
You might be familiar with the browser's localStorage. While similar in purpose, chrome.storage is generally preferred for extensions due to key differences:
- Asynchronous:
chrome.storageis async,localStorageis sync (can block UI). - Security:
chrome.storageis scoped to your extension. - Syncing: Only
chrome.storage.syncoffers cross-device syncing. - Availability:
chrome.storageworks in service workers,localStoragedoes not.
Saving Data with .set()
To save data, use the .set() method. It takes an object where keys are strings and values can be any JSON-serializable type.
This example saves a user's favorite color. This code would run in your extension's background script.
/* This code would typically run in your background.js */
/* (manifest.json would declare it as a service_worker) */
// Save a single item to local storage
chrome.storage.local.set({ 'favoriteColor': 'blue' }, function() {
if (chrome.runtime.lastError) {
console.error("Error saving color: ", chrome.runtime.lastError);
} else {
console.log("Favorite color saved!");
}
});
// Save multiple items to sync storage
chrome.storage.sync.set({
'userName': 'Coddy',
'darkMode': true
}, function() {
if (chrome.runtime.lastError) {
console.error("Error saving user settings: ", chrome.runtime.lastError);
} else {
console.log("User settings saved to sync!");
}
});Retrieving Data with .get()
To get data back, use the .get() method. You can specify keys, or pass null to get all items.
The callback function receives an object containing the requested data, or an empty object if the key isn't found.
/* This code would typically run in your background.js */
// Get a single item from local storage
chrome.storage.local.get('favoriteColor', function(data) {
const color = data.favoriteColor;
if (color) {
console.log("Your favorite color is: " + color);
} else {
console.log("Favorite color not set locally.");
}
});
// Get multiple items from sync storage
chrome.storage.sync.get(['userName', 'darkMode'], function(data) {
const userName = data.userName || 'Guest';
const darkMode = data.darkMode || false;
console.log(`Hello, ${userName}! Dark mode: ${darkMode}`);
});
// Get all items from local storage (use with caution for large data)
chrome.storage.local.get(null, function(data) {
console.log("All local storage data:", data);
});Removing Data: .remove() & .clear()
Sometimes you need to delete stored data. You can remove specific items or clear all data for your extension.
.remove(keys): Deletes one or more specific items..clear(): Removes all data from the storage area for your extension.
/* This code would typically run in your background.js */
// Remove a single item from local storage
chrome.storage.local.remove('favoriteColor', function() {
if (chrome.runtime.lastError) {
console.error("Error removing color: ", chrome.runtime.lastError);
} else {
console.log("Favorite color removed from local storage.");
}
});
// Remove multiple items from sync storage
chrome.storage.sync.remove(['userName', 'darkMode'], function() {
if (chrome.runtime.lastError) {
console.error("Error removing settings: ", chrome.runtime.lastError);
} else {
console.log("User settings removed from sync storage.");
}
});
// Clear all data from local storage (use with extreme caution!)
// chrome.storage.local.clear(function() {
// if (chrome.runtime.lastError) {
// console.error("Error clearing local storage: ", chrome.runtime.lastError);
// } else {
// console.log("Local storage cleared!");
// }
// });Listening for Storage Changes
Your extension can react when its stored data changes using the chrome.storage.onChanged event listener.
This is useful if different parts of your extension (like a popup and a background script) need to know when data is updated.
The listener provides details about what changed (newValue, oldValue) and in which storage area (local, sync).
/* This code would typically run in your background.js */
chrome.storage.onChanged.addListener(function(changes, areaName) {
console.log("Storage area '" + areaName + "' changed.");
for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Key "${key}" changed. ` +
`Old value was "${oldValue}", new value is "${newValue}".`
);
}
});
// To demonstrate, let's change a value after a short delay
setTimeout(() => {
chrome.storage.local.set({'favoriteColor': 'green'}, function() {
if (!chrome.runtime.lastError) {
console.log("Color updated to trigger onChanged listener.");
}
});
}, 2000);Declaring the Storage Permission
To use the chrome.storage API, your extension needs to declare the "storage" permission in its manifest.json file.
Without this permission, attempts to use chrome.storage will fail with an error, and your extension won't be able to save or retrieve data.
{
"manifest_version": 3,
"name": "My Storage Extension",
"version": "1.0",
"permissions": [
"storage"
],
"background": {
"service_worker": "background.js"
}
}Storage API Quick Check
Which of the following statements about chrome.storage are TRUE?
Recap: Mastering Data Persistence
You've learned how to persist data in your browser extensions using the chrome.storage API!
- We covered
.localfor browser-specific data and.syncfor cross-device syncing. - You now know how to
.set(),.get(),.remove(), and.clear()data. - We also explored reacting to changes with
.onChangedand the crucial"storage"permission.
This knowledge is vital for building robust and user-friendly extensions that remember user preferences and states.
常见问题解答
「使用 Chrome Storage API」课时是免费的吗?
是的 — 「使用 Chrome Storage API」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Browser Extensions Development (Chrome & Edge) 课程的其余内容,请升级到 CoddyKit PRO。 Browser Extensions Development (Chrome & Edge) 课程共包含 4 节课。
「使用 Chrome Storage API」这节课中我会学到什么?
使用 `chrome.storage` API 安全高效地持久化用户设置和数据,并实现本地存储与同步存储 你通过在浏览器中直接运行的动手代码来练习 Browser Extensions Development (Chrome & Edge),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Browser Extensions Development (Chrome & Edge) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Browser Extensions Development (Chrome & Edge) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 Chrome Storage API」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Browser Extensions Development (Chrome & Edge) 课中编写并运行代码吗?
能。每节 Browser Extensions Development (Chrome & Edge) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 单向消息传递模式
- 组件之间的双向消息传递
- 使用 Chrome Storage API
- 同步存储与本地存储及配额