Chrome Storage API 사용
로컬 저장소와 동기화 저장소에 사용자 설정과 데이터를 안전하고 효율적으로 보존하는 방법을 `chrome.storage` API를 사용해 학습합니다.
Chrome Storage API 사용은(는) CoddyKit의 무료 Browser Extensions Development (Chrome & Edge) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 사용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Browser Extensions Development (Chrome & Edge) 강의 전체를 잠금 해제할 수 있습니다. Browser Extensions Development (Chrome & Edge) 강의에는 총 4개의 강의가 포함되어 있습니다.
“Chrome Storage API 사용”에서 뭘 배우나요?
로컬 저장소와 동기화 저장소에 사용자 설정과 데이터를 안전하고 효율적으로 보존하는 방법을 `chrome.storage` API를 사용해 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Browser Extensions Development (Chrome & Edge)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Browser Extensions Development (Chrome & Edge)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Browser Extensions Development (Chrome & Edge)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Chrome Storage API 사용” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Browser Extensions Development (Chrome & Edge) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Browser Extensions Development (Chrome & Edge) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 단방향 메시징 패턴
- 구성 요소 간 양방향 메시징
- Chrome Storage API 사용
- 동기화 저장소와 로컬 저장소 및 할당량