IndexedDB — низкоуровневое API для клиентского хранилища большого объема структурированных данных, включая файлы/blobs. Эти API используют индексы для обеспечения высоко-производительного поиска данных. Если DOM Storage  полезен для хранения небольшого количества данных, он менее выгоден для большого числа структурированных данных. IndexedDB предоставляет решение. Это основная страница на MDN, покрывающая IndexedDB — здесь мы предоставляем ссылки к полному списку API и руководствам по использованию, детали поддержки браузерами и некоторые объяснения ключевых концепций.

Примечание: Эта возможность доступна в Web Workers.

Заметка: IndexedDB API мощные, но могут казаться слишком сложными для простых задач. Если вы предпочитаете простые API, попробуйте библиотеки, такие как localForage, dexie.js и ZangoDB, делающие IndexedDB более дружественным.

Ключевые концепции и  использование

IndexedDB транзакционная система базы данных, как SQL-основанная RDBMS. Однако, в отличие от RDBMS, которая использует таблицы с фиксированными колонками, IndexedDB — JavaScript-основанная объектно-ориентированная база данных. IndexedDB позволяет сохранять и возвращать объекты, которые были проиндексированы с ключом; любой объект, поддерживаемый структурированным алгоритмом клонирования может быть сохранен. Необходимо описать схему базы данных, установить соединение с ней и затем получить и обновить данные за несколько транзакций.

  • Читайте больше о Концепции IndexedDB.
  • Изучите асинхронное использование IndexedDB по первоначальным принципам с руководством Using IndexedDB.
  • Найдите рекомендации по разработке, чтобы заставить ваш сайт работать вне сети, на странице Offline Apps.

Заметка: Как и большинство решений web-хранения, IndexedDB следует аналогичной same-origin policy. Поэтому вы имеете доступ к хранилищу данных в пределах одного домена, но не можете получать их с любого другого.

Синхронность и асинхронность

Operations performed using IndexedDB are done asynchronously, so as not to block applications. IndexedDB originally included both synchronous and asynchronous APIs. The synchronous API was intended for use only with Web Workers, but was removed from the spec because it was unclear whether it was needed. However,  the synchronous API may be reintroduced if there is enough demand from web developers.

Storage limits and eviction criteria

There are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). IndexedDB is the most commonly talked about one. The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. Browser storage limits and eviction criteria attempts to explain how this works, at least in the case of Firefox.

Interfaces

To get access to a database, call open() on the indexedDB attribute of a window object. This method returns an IDBRequest object; asynchronous operations communicate to the calling application by firing events on IDBRequest objects.

Connecting to a database

IDBEnvironment
Provides access to IndexedDB functionality. It is implemented by the window and worker objects.
IDBFactory
Provides access to a database. This is the interface implemented by the global object indexedDB and is therefore the entry point for the API.
IDBOpenDBRequest
Represents a request to open a database.
IDBDatabase
Represents a connection to a database. It's the only way to get a transaction on the database.
Retrieving and modifying data
IDBTransaction
Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.
IDBRequest
Generic interface that handles database requests and provides access to results.
IDBObjectStore
Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.
IDBIndex
Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using IDBObjectStore.
IDBCursor
Iterates over object stores and indexes.
IDBCursorWithValue
Iterates over object stores and indexes and returns the cursor's current value.
IDBKeyRange
Defines a key range that can be used to retrieve data from a database in a certain range.
IDBLocaleAwareKeyRange
Defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createIndex()'s optionalParameters.).

Custom event interfaces

This specification fires events with the following custom interface:

IDBVersionChangeEvent
The IDBVersionChangeEvent interface indicates that the version of the database has changed, as the result of an IDBOpenDBRequest.onupgradeneeded event handler function.

Obsolete interfaces

An early version of the specification also defined these now removed interfaces. They are still documented in case you need to update previously written code:

IDBVersionChangeRequest
Represents a request to change the version of a database. The way to change the version of the database has since changed (by calling IDBFactory.open without also calling IDBDatabase.setVersion), and the interface IDBOpenDBRequest now has the functionality of the removed IDBVersionChangeRequest.
IDBDatabaseException 
Represents exception conditions that can be encountered while performing database operations.
IDBTransactionSync
Sync version of IDBTransaction.
IDBObjectStoreSync
Sync version of IDBObjectStore.
IDBIndexSync
Sync version of IDBIndex.
IDBFactorySync
Sync version of IDBFactory.
IDBEnvironmentSync
Sync version of IDBEnvironment.
IDBDatabaseSync
Sync version of IDBDatabase.
IDBCursorSync
Sync version of IDBCursor.

Examples

Specifications

Specification Status Comment
Indexed Database API Рекомендация Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer/Edge Opera Safari (WebKit)
Basic support 23webkit
24 (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
10.0 (10.0) moz
16.0 (16.0)
10, partial 15

7.1, partial
10

Available in workers (Да) (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
37.0 (37.0)[1] (Да) (Да) 10
Available in privacy mode (Да) Нет Нет Нет Нет
IDBLocaleAwareKeyRange Нет 43.0 (43.0)[2] Нет Нет Нет
Feature Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE/Edge Phone Opera Mobile Safari Mobile
Basic support (Да) (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
(Да) (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
22.0 (22.0) 1.0.1 10, partial 22 8, partial
10
Available in workers (Да) (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
(Да) (unprefixed)
38 (prefixes deprecated)
57 (prefixes removed)
37.0 (37.0)[1] (Да) (Да) (Да) 10
Available in privacy mode Нет Нет Нет Нет Нет ? ?
IDBLocaleAwareKeyRange Нет Нет 43.0 (43.0)[2] 2.5[2] Нет Нет Нет
  • [1] IDBCursorWithValue is not available in workers until Gecko 42.0 (Firefox 42.0 / Thunderbird 42.0 / SeaMonkey 2.39).
  • [2] This feature is currently hidden behind a flag — to enable it and experiment, go to about:config and enable dom.indexedDB.experimental.
  • [3] AKA "Private Browsing Mode" (Firefox) and "Incognito" (Chrome).

See also

  • localForage: A Polyfill providing a simple name:value syntax for client-side data storage, which uses IndexedDB in the background, but falls back to WebSQL and then localStorage in browsers that don't support IndexedDB.
  • dexie.js: A wrapper for IndexedDB that allows much faster code development via nice, simple syntax.
  • ZangoDB: A MongoDB-like interface for IndexedDB that supports most of the familiar filtering, projection, sorting, updating and aggregation features of MongoDB.

Метки документа и участники

 Внесли вклад в эту страницу: amelk9n, karatheodory, curdwithraisins, Skholastik, madarche
 Обновлялась последний раз: amelk9n,