A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.chrome.com/docs/extensions/reference/api/storage below:

chrome.storage | API | Chrome for Developers

Skip to main content chrome.storage

Stay organized with collections Save and categorize content based on your preferences.

Description

Use the chrome.storage API to store, retrieve, and track changes to user data.

Permissions

storage

To use the storage API, declare the "storage" permission in the extension manifest. For example:

{
  "name": "My extension",
  ...
  "permissions": [
    "storage"
  ],
  ...
}
Concepts and usage

The Storage API provides an extension-specific way to persist user data and state. It's similar to the web platform's storage APIs (IndexedDB, and Storage), but was designed to meet the storage needs of extensions. The following are a few key features:

Can extensions use web storage APIs?

While extensions can use the Storage interface (accessible from window.localStorage) in some contexts (popup and other HTML pages), we don't recommend it for the following reasons:

To move data from web storage APIs to extension storage APIs from a service worker:

  1. Prepare an offscreen document html page and script file. The script file should contain a conversion routine and an onMessage handler.
  2. In the extension service worker, check chrome.storage for your data.
  3. If your data isn't found, call createDocument().
  4. After the returned Promise resolves, call sendMessage() to start the conversion routine.
  5. Inside the offscreen document's onMessage handler, call the conversion routine.

There are also some nuances to how web storage APIs work in extensions. Learn more in the Storage and Cookies article.

Storage areas

The Storage API is divided into the following storage areas:

storage.local
Data is stored locally and cleared when the extension is removed. The storage limit is 10 MB (5 MB in Chrome 113 and earlier), but can be increased by requesting the "unlimitedStorage" permission. We recommend using storage.local to store larger amounts of data. By default, it's exposed to content scripts, but this behavior can be changed by calling chrome.storage.local.setAccessLevel().
storage.managed
Managed storage is read-only storage for policy installed extensions and managed by system administrators using a developer-defined schema and enterprise policies. Policies are analogous to options but are configured by a system administrator instead of the user, allowing the extension to be preconfigured for all users of an organization. For information on policies, see Documentation for Administrators. To learn more about the managed storage area, see Manifest for storage areas.
storage.session
Holds data in memory while an extension is loaded. The storage is cleared if the extension is disabled, reloaded or updated and when the browser restarts. By default, it's not exposed to content scripts, but this behavior can be changed by calling chrome.storage.session.setAccessLevel(). The storage limit is 10 MB (1 MB in Chrome 111 and earlier). Thestorage.session interface is one of several we recommend for service workers.
storage.sync
If syncing is enabled, the data is synced to any Chrome browser that the user is logged into. If disabled, it behaves like storage.local. Chrome stores the data locally when the browser is offline and resumes syncing when it's back online. The quota limitation is approximately 100 KB, 8 KB per item. We recommend using storage.sync to preserve user settings across synced browsers. If you're working with sensitive user data, instead use storage.session. By default, storage.sync is exposed to content scripts, but this behavior can be changed by calling chrome.storage.sync.setAccessLevel().
Storage and throttling limits

The Storage API has the following usage limitations:

For details on storage area limitations and what happens when they're exceeded, see the quota information for sync, local, and session.

Use cases

The following sections demonstrate common use cases for the Storage API.

Respond to storage updates

To track changes made to storage, add a listener to its onChanged event. When anything changes in storage, that event fires. The sample code listens for these changes:

background.js:

chrome.storage.onChanged.addListener((changes, namespace) => {
  for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
    console.log(
      `Storage key "${key}" in namespace "${namespace}" changed.`,
      `Old value was "${oldValue}", new value is "${newValue}".`
    );
  }
});

We can take this idea even further. In this example, we have an options page that allows the user to toggle a "debug mode" (implementation not shown here). The options page immediately saves the new settings to storage.sync, and the service worker uses storage.onChanged to apply the setting as soon as possible.

options.html:

<!-- type="module" allows you to use top level await -->
<script defer src="options.js" type="module"></script>
<form id="optionsForm">
  <label for="debug">
    <input type="checkbox" name="debug" id="debug">
    Enable debug mode
  </label>
</form>

options.js:

// In-page cache of the user's options
const options = {};
const optionsForm = document.getElementById("optionsForm");

// Immediately persist options changes
optionsForm.debug.addEventListener("change", (event) => {
  options.debug = event.target.checked;
  chrome.storage.sync.set({ options });
});

// Initialize the form with the user's option settings
const data = await chrome.storage.sync.get("options");
Object.assign(options, data.options);
optionsForm.debug.checked = Boolean(options.debug);

background.js:

function setDebugMode() { /* ... */ }

// Watch for changes to the user's options & apply them
chrome.storage.onChanged.addListener((changes, area) => {
  if (area === 'sync' && changes.options?.newValue) {
    const debugMode = Boolean(changes.options.newValue.debug);
    console.log('enable debug mode?', debugMode);
    setDebugMode(debugMode);
  }
});
Asynchronous preload from storage

Because service workers don't run all the time, Manifest V3 extensions sometimes need to asynchronously load data from storage before they execute their event handlers. To do this, the following snippet uses an async action.onClicked event handler that waits for the storageCache global to be populated before executing its logic.

background.js:

// Where we will expose all the data we retrieve from storage.sync.
const storageCache = { count: 0 };
// Asynchronously retrieve data from storage.sync, then cache it.
const initStorageCache = chrome.storage.sync.get().then((items) => {
  // Copy the data retrieved from storage into storageCache.
  Object.assign(storageCache, items);
});

chrome.action.onClicked.addListener(async (tab) => {
  try {
    await initStorageCache;
  } catch (e) {
    // Handle error that occurred during storage initialization.
  }

  // Normal action handler logic.
  storageCache.count++;
  storageCache.lastTabId = tab.id;
  chrome.storage.sync.set(storageCache);
});

You can view and edit data stored using the API in DevTools. To learn more, see the View and edit extension storage page in the DevTools documentation.

Examples

The following samples demonstrate the local, sync, and session storage areas:

Local
chrome.storage.local.set({ key: value }).then(() => {
  console.log("Value is set");
});

chrome.storage.local.get(["key"]).then((result) => {
  console.log("Value is " + result.key);
});
Sync
chrome.storage.sync.set({ key: value }).then(() => {
  console.log("Value is set");
});

chrome.storage.sync.get(["key"]).then((result) => {
  console.log("Value is " + result.key);
});
Session
chrome.storage.session.set({ key: value }).then(() => {
  console.log("Value was set");
});

chrome.storage.session.get(["key"]).then((result) => {
  console.log("Value is " + result.key);
});

To see other demos of the Storage API, explore any of the following samples:

Types

AccessLevel

The storage area's access level.

Enum

"TRUSTED_CONTEXTS"
Specifies contexts originating from the extension itself.

"TRUSTED_AND_UNTRUSTED_CONTEXTS"
Specifies contexts originating from outside the extension.

Properties Properties Properties

local

Items in the local storage area are local to each machine.

Properties

managed

Items in the managed storage area are set by an enterprise policy configured by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. For information on configuring a policy, see Manifest for storage areas.

session

Items in the session storage area are stored in-memory and will not be persisted to disk.

Properties

sync

Items in the sync storage area are synced using Chrome Sync.

Properties Events

onChanged

chrome.storage.onChanged.addListener(
  callback: function,
)

Fired when one or more items change.

Parameters

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-11 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-07-11 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4