chrome.storage

您所在的位置:网站首页 propertysetstorage chrome.storage

chrome.storage

#chrome.storage| 来源: 网络整理| 查看: 265

# Overview

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 localStorage), but was designed to meet the storage needs of extensions. The following are a few key features:

All extension contexts, including the extension service worker and content scripts have access to the Storage API.The JSON serializable values are stored as object properties.The Storage API is asynchronous with bulk read and write operations.Even if the user clears the cache and browsing history, the data persists.Stored settings persist even when using split incognito.Includes an exclusive read-only managed storage area for enterprise policies.

💡 Can extensions use the WebStorage API?

Even though extensions can access Window.localStorage in some contexts (popup and other HTML pages), it is not recommended for the following reasons:

The extension's service worker cannot access Window.localStorage.Content scripts share the Window.localStorage of the host page.Data saved to Window.localStorage is lost when the user clears their browsing history.# Storage areas

The Storage API is divided into the following four buckets ("storage areas"):

storage.localData is stored locally, which is cleared when the extension is removed. The quota limitation is approx 5 MB, but can be increased by requesting the "unlimitedStorage" permission. Consider using it to store larger amounts of data.storage.syncIf syncing is enabled, the data is synced to any Chrome browser that the user is logged into. If disabled, it behaves like storage.local. When the browser is offline, Chrome stores the data locally and resumes syncing when it's back online. The quota limitation is 100 KB approx, 8 KB per item. Consider using it to preserve user settings across synced browsers.Warning

Local and sync storage areas should not store confidential user data because they are not encrypted. When working with sensitive data, consider using the session storage area to hold values in memory until the browser is shut down.

storage.sessionHolds data in memory for the duration of a browser session. By default, it's not exposed to content scripts, but this behavior can be changed by setting chrome.storage.session.setAccessLevel(). The quota limitation is approximately 10 MB. Consider using it to store global variables across service worker runs.Warning

Before Chrome 112, the quota was approximately 1 MB.

storage.managedAdministrator can use a schema and enterprise policies to configure a supporting extension's settings in a managed environment. This storage area is read-only.# Manifest

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

{ "name": "My extension", ... "permissions": [ "storage" ], ...}# Usage

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

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

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

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

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

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

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

To learn more about the managed storage area, see Manifest for storage areas.

# Storage and throttling limits

Don't think of adding to the Storage API as putting things in a big truck. Think of adding to storage as being like putting something in a pipe. The pipe may have material in it already, and it may even be filled. Always assume a delay between when you add to storage and when it is actually recorded.

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

# Use cases

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

# Synchronous response to storage updates

To track changes made to storage, you can 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:

Enable debug mode

options.js:

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

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

// Initialize the form with the user's option settingsconst 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 themchrome.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

Since service workers are not always running, 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);});

# Extension examples

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

Global search extension.Water alarm extension.


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3