Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

IndexedDB 是一种使用浏览器存储大量数据的方法.它创造的数据可以被查询,并且可以离线使用. IndexedDB对于那些需要存储大量数据,或者是需要离线使用的程序是非常有效的解决方法.

关于本文档

本文档介绍IndexedDB的基本概念. 它给你一个清晰的构架图. 想学到更多,查看 Definitions部分.

使用 IndexedDB 有一个说明如何使用API的教程.  IndexedDB API的参考手册详见 IndexedDB 文章及其子页面,它们描述了 indexedDB 所使用的对象类型,以及同步和异步api的相关方法.

 IndexedDB概况

使用IndexedDB,你可以存储或者获取数据,使用一个key索引的。 你可以在事务(transaction)中完成对数据的修改。和大多数web存储解决方案相同,indexedDB也遵从同源协议(same-origin policy). 所以你只能访问同域中存储的数据,而不能访问其他域的。

API包含异步(asynchronous) API 和同步(synchronous)API两种。  异步API适合大多数情况, 同步API必须同 WebWorkers一同使用. 目前,没有主流浏览器支持同步API。 即使同步API被支持了,你也会在大多数的情况使用异步API。

IndexedDB 是 WebSQL 数据库的取代品, W3C组织在2010年11月18日废弃了webSql.  IndexedDB 和WebSQL的不同点在于WebSQL 是关系型数据库(复杂)IndexedDB 是key-value型数据库(简单好使).

基本概念

像其他key-value数据库一样(不是关系型数据库,nosql的):

  • IndexedDB 数据库使用key-value键值对储存数据. values 数据可以是非常复杂的结构体.

  • IndexedDB 是事务模式的数据库. 任何操作都发生在事务(transaction)中。  IndexedDB API提供了索引, 表, 指针等等, 但是所有这些必须是依赖于某种事务的。 你不能在事务外执行命令或者打开指针.

    事务(transaction)有生存周期, 在生存周期以后使用它会报错。并且,事务(transaction)是自动提交的,不可以手动提交。

    当用户在不同的标签页同时打开Web应用的两个实例时,这个事务模型就会非常有用。如果没有事务操作的支持,这两个实例就会互相影响对方的修改。如果你不熟悉数据库的事务模型,请参考数据库事务(维基百科)。 同时参考transaction文章中关于事务的定义部分。

  • The IndexedDB API 基本上是异步的. IndexedDB的API不通过return语句返回数据,而是需要你提供一个回调函数来接受数据。执行API时,你不以同步(synchronous)方式对数据库进行“存储”和“读取”操作,而是向数据库发送一个操作“请求”。当操作完成时,数据库会以DOM事件的方式通知你,同时事件的类型会告诉你这个操作是否成功完成。这个过程听起来会有些复杂,但是里面是有明智的原因的。这个和XMLHttpRequest请求是类似的。

  • IndexedDB 是面向对象的。

    IndexedDB 不使用SQL. 它属于noSQL数据库。

  • IndexedDB数据库“请求”无处不在 我们上边提到,数据库“请求”负责接受成功或失败的DOM事件。每一个“请求”都包含onsuccessonerror属性,同时你还对“请求”调用addEventListener()和removeEventListener()。“请求”还包括readyStateresulterrorCode属性,用来表示“请求”的状态。result属性尤其魔幻,他可以根据“请求”生成的方式变成不同的东西,例如:IDBCursor实例、刚插入数据库的数值对应的键值(key)等

  • IndexedDB在结果准备好之后通过DOM事件通知用户 DOM事件总是有一个类型(type)属性(在IndexedDB中,该属性通常设置为successerror)。DOM事件还有一个目标(target)属性,用来告诉事件是在哪里触发的。通常情况下,目标(target)属性是数据库操作生成的IDBRequest。成功(success)事件不弹出提示并且不能撤销,错误(error)事件会弹出提示且可以撤销。这一点是非常重要的,因为除非错误事件被撤销,否则他们会终止所在的任何事务。

  • IndexedDB遵循同源(same-origin)策略 “源”指脚本所在文档URL的域名、应用层协议和端口。每一个“源”都有与其相关联的数据库。在同一个“源”内的所有数据库都有唯一、可区别的名称。

    IndexedDB的安全机制避免应用访问非同“源”的数据。例如,https://www.example.com/app/的应用或页面可以访问https://www.example.com/dir/的数据,因为他们同“源”。但是它们不能访问https://www.example.com:8080/dir/(不同端口)或https://www.example.com/dir/(不同协议)的数据,因为他们不同“源”。

名词解释

本节定义并解释了IndexedDB API中所使用的术语

数据库

数据库
一个信息库,通常包含一个或多个 object stores. 每个数据库必须包含以下内容:
  • 名字(Name). 它标识了一个特定源中的数据库,并且在数据库的整个生命周期内保持不变.  此名字可以为任意字符串值(包括空字符串).
  • 当前版本(version). 当一个数据库首次创建时,它的 version 为1,除非另外指定. 每个数据库在任意时刻只能有一个 version.
对象存储(object store)

数据在数据库中存储的方式, 数据以键值对形式被对象存储永久持有. 对象存储中的的数据以 keys 升序排列.

每一个对象存储在同一个数据库中必须有唯一的名字. 对象存储可以有一个 key generator 和一个 key path. 如果对象存储有 key path, 则使用 in-line keys; 否则使用 out-of-line keys.

关于对象存储的详细文档, 请参考 IDBObjectStore 或者 IDBObjectStoreSync.

version
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a VERSION_CHANGE transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
Note: This definition describes the most recent specifications, which is only implemented in some up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
database connection
An operation created by opening a database. A given database can have multiple connections at the same time.
transaction

An atomic and durable set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

A database connection can have several active transaction associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them—even overlapping ones.

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

The three modes of transactions are: read/write, read only, and version change. The only way to create and delete object stores and indexes is by using a version-change transaction. To learn more about transaction types, see the reference article for IndexedDB.

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how it relates to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

request
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
index

A specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refers to the object store are automatically updated.

Alternatively, you can also look up records in an object store using the key.

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.



 

Key and value

key

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, and an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

A key can be one of the following type: string, date, float, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array. Note that Firefox prior to 11 only accepted keys of type string or integer.

Alternatively, you can also look up records in an object store using the index.

key generator
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
in-line key
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
out-of-line key
A key that is stored separately from the value being stored.
key path
Defines where the browser should extract the key from a value in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods. It cannot include spaces.
value

Each record has a value, which could include anything that can be expressed in JavaScript, including: boolean, number, string, date, object, array, regexp, undefined, and null.

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

The specification lets you store files and blobs, but this has only been implemented in Firefox 11+.

Range and scope

scope
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
cursor
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
key range

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

For the reference documentation on key range, see IDBKeyRange.

局限性

以下情况不适合使用IndexedDB

  • 全球多种语言混合存储。国际化支持不好。需要自己处理。
  • 和服务器端数据库同步。你得自己写同步代码。
  • 全文搜索。

注意,在以下情况下,数据库可能被清除:

  • 用户请求清除数据。
  • 浏览器处于隐私模式。最后退出浏览器的时候,数据会被清楚。
  • 硬盘等存储设备的容量到限。
  • 不正确的
  • 不完整的改变.

下一步

查看如何使用的文档: Using IndexedDB.

相关文章

标准

参考手则

教程

其他文章

文档标签和贡献者

 此页面的贡献者: ywwzwb, ziyunfei, mountainmoon, Fify, teoli, goldWind, karsa.si
 最后编辑者: ywwzwb,