浏览器快捷键指南_快速但完整的IndexedDB指南以及在浏览器中存储数据
瀏覽器快捷鍵指南
Interested in learning JavaScript? Get my JavaScript ebook at jshandbook.com
有興趣學(xué)習(xí)JavaScript嗎? 在jshandbook.com上獲取我JavaScript電子書
IndexedDB簡介 (Introduction to IndexedDB)
IndexedDB is one of the storage capabilities introduced into browsers over the years. It's a key/value store (a noSQL database) considered to be the definitive solution for storing data in browsers.
IndexedDB是多年來瀏覽器引入的存儲功能之一。 它是鍵/值存儲(noSQL數(shù)據(jù)庫),被認(rèn)為是在瀏覽器中存儲數(shù)據(jù)的最終解決方案 。
It's an asynchronous API, which means that performing costly operations won't block the UI thread providing a sloppy experience to users. It can store an indefinite amount of data, although once over a certain threshold the user is prompted to give the site higher limits.
這是一個異步API,這意味著執(zhí)行昂貴的操作不會阻止UI線程,從而為用戶提供草率的體驗(yàn)。 它可以存儲無限量的數(shù)據(jù),盡管一旦超過某個閾值,系統(tǒng)會提示用戶為站點(diǎn)提供更高的限制。
It's supported on all modern browsers.
所有現(xiàn)代瀏覽器均支持該功能 。
It supports transactions, versioning and gives good performance.
它支持事務(wù),版本控制并提供良好的性能。
Inside the browser we can also use:
在瀏覽器內(nèi)部,我們還可以使用:
Cookies: can host a very small amount of strings
Cookies :可以容納很少量的字符串
Web Storage (or DOM Storage), a term that commonly identifies localStorage and sessionStorage, two key/value stores. sessionStorage, does not retain data, which is cleared when the session ends, while localStorage keeps the data across sessions
Web存儲 (或DOM存儲),一個通常標(biāo)識localStorage和sessionStorage這兩個鍵/值存儲的術(shù)語。 sessionStorage不保留數(shù)據(jù),該數(shù)據(jù)在會話結(jié)束時被清除,而localStorage在會話之間保留數(shù)據(jù)
Local/session storage have the disadvantage of being capped at a small (and inconsistent) size, with browsers implementation offering from 2MB to 10MB of space per site.
本地/會話存儲的缺點(diǎn)是限制在較小(且不一致)的大小,每個站點(diǎn)的瀏覽器實(shí)現(xiàn)提供2MB到10MB的空間。
In the past we also had Web SQL, a wrapper around SQLite, but now this is deprecated and unsupported on some modern browsers, it's never been a recognized standard and so it should not be used, although 83% of users have this technology on their devices according to Can I Use.
過去我們也有Web SQL ,它是圍繞SQLite的包裝,但是現(xiàn)在已經(jīng)不推薦使用,并且在某些現(xiàn)代瀏覽器中不支持此包裝,盡管它有83%的用戶在其上使用了此技術(shù),但它從未被公認(rèn)是標(biāo)準(zhǔn),因此不應(yīng)該使用它。 根據(jù)我可以使用的設(shè)備 。
While you can technically create multiple databases per site, you generally create one single database, and inside that database you can create multiple object stores.
從技術(shù)上講,每個站點(diǎn)可以創(chuàng)建多個數(shù)據(jù)庫,但是通常可以創(chuàng)建一個數(shù)據(jù)庫 ,并且可以在該數(shù)據(jù)庫內(nèi)部創(chuàng)建多個對象存儲 。
A database is private to a domain, so any other site cannot access another website IndexedDB stores.
數(shù)據(jù)庫是域?qū)S玫?/strong> ,因此任何其他站點(diǎn)都無法訪問其他網(wǎng)站IndexedDB存儲。
Each store usually contains a set of things, which can be
每個商店通常包含一組東西 ,可以是
- strings 弦
- numbers 數(shù)字
- objects 對象
- arrays 數(shù)組
- dates 日期
For example you might have a store that contains posts, another that contains comments.
例如,您可能有一個包含帖子的商店,另一個包含評論的商店。
A store contains a number of items which have a unique key, which represents the way by which an object can be identified.
商店包含許多具有唯一密鑰的項(xiàng)目,該唯一密鑰表示識別對象的方式。
You can alter those stores using transactions, by performing add, edit and delete operations, and iterating over the items they contain.
您可以通過執(zhí)行添加,編輯和刪除操作,以及遍歷它們包含的項(xiàng)目來使用事務(wù)來更改這些商店。
Since the advent of Promises in ES6, and the subsequent move of APIs to using promises, the IndexedDB API seems a bit old school.
自從ES6中Promises的問世以及API后來轉(zhuǎn)向使用Promise以來,IndexedDB API似乎有點(diǎn)老套了 。
While there's nothing wrong in it, in all the examples that I'll explain I'll use the IndexedDB Promised Library by Jake Archibald, which is a tiny layer on top of the IndexedDB API to make it easier to use.
盡管沒有什么錯,但在所有要解釋的示例中,我將使用Jake Archibald 編寫的IndexedDB Promised Library ,它是IndexedDB API之上的一小層,使它易于使用。
This library is also used on all the examples on the Google Developers website regarding IndexedDB
該庫還用于Google Developers網(wǎng)站上有關(guān)IndexedDB的所有示例中
創(chuàng)建一個IndexedDB數(shù)據(jù)庫 (Create an IndexedDB Database)
The simplest way is to use unpkg, by adding this to the page header:
最簡單的方法是使用unpkg ,方法是將其添加到頁面標(biāo)題中:
<script type="module"> import { openDB, deleteDB } from 'https://unpkg.com/idb?module' </script>Before using the IndexedDB API, always make sure you check for support in the browser, even though it's widely available, you never know which browser the user is using:
在使用IndexedDB API之前,請務(wù)必確保檢查瀏覽器是否提供支持,即使該支持廣泛可用,也永遠(yuǎn)不會知道用戶使用的是哪種瀏覽器:
(() => {'use strict'if (!('indexedDB' in window)) {console.warn('IndexedDB not supported')return}//...IndexedDB code })()如何建立資料庫 (How to create a database)
Using openDB():
使用openDB() :
(async () => {//...const dbName = 'mydbname'const storeName = 'store1'const version = 1 //versions start at 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)}}) })()The first 2 parameters are the database name, and the verson. The third param, which is optional, is an object that contains a function called only if the version number is higher than the current installed database version. In the function body you can upgrade the structure (stores and indexes) of the db.
前兩個參數(shù)是數(shù)據(jù)庫名稱和版本。 第三個參數(shù)是可選的,它是一個對象,其中包含僅當(dāng)版本號高于當(dāng)前已安裝的數(shù)據(jù)庫版本時才調(diào)用的函數(shù)。 在功能主體中,您可以升級數(shù)據(jù)庫的結(jié)構(gòu)(存儲和索引)。
將數(shù)據(jù)添加到存儲中 (Adding data into a store)
創(chuàng)建商店時添加數(shù)據(jù),對其進(jìn)行初始化 (Adding data when the store is created, initializing it)
You use the put method of the object store, but first we need a reference to it, which we can get from db.createObjectStore() when we create it.
您使用對象存儲的put方法,但是首先我們需要對其進(jìn)行引用,我們可以在創(chuàng)建它時從db.createObjectStore()獲取它。
When using put, the value is the first argument, the key is the second. This is because if you specify keyPath when creating the object store, you don't need to enter the key name on every put() request, you can just write the value.
使用put ,值是第一個參數(shù),鍵是第二個參數(shù)。 這是因?yàn)?#xff0c;如果在創(chuàng)建對象存儲庫時指定keyPath ,則無需在每個put()請求中都輸入鍵名,只需編寫該值即可。
This populates store0 as soon as we create it:
我們創(chuàng)建后立即填充store0 :
(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(dbName, version,{upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)store.put('Hello world!', 'Hello')}}) })()使用事務(wù)在創(chuàng)建商店后添加數(shù)據(jù) (Adding data when the store is already created, using transactions)
To add items later down the road, you need to create a read/write transaction, that ensures database integrity (if an operation fails, all the operations in the transaction are rolled back and the state goes back to a known state).
要在以后添加項(xiàng)目,您需要創(chuàng)建一個讀/寫事務(wù) ,以確保數(shù)據(jù)庫完整性(如果操作失敗,則事務(wù)中的所有操作都會回滾,并且狀態(tài)返回到已知狀態(tài))。
For that, use a reference to the dbPromise object we got when calling openDB, and run:
為此,請使用對調(diào)用openDB時獲得的dbPromise對象的引用,然后運(yùn)行:
(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(/* ... */)const tx = db.transaction(storeName, 'readwrite')const store = await tx.objectStore(storeName)const val = 'hey!'const key = 'Hello again'const value = await store.put(val, key)await tx.done })()從商店獲取數(shù)據(jù) (Getting data from a store)
從商店獲取一件商品: get() (Getting one item from a store: get())
const key = 'Hello again' const item = await db.transaction(storeName).objectStore(storeName).get(key)從商店獲取所有商品: getAll() (Getting all the items from a store: getAll())
Get all the keys stored
獲取所有存儲的密鑰
const items = await db.transaction(storeName).objectStore(storeName).getAllKeys()Get all the values stored
獲取所有存儲的值
const items = await db.transaction(storeName).objectStore(storeName).getAll()從IndexedDB刪除數(shù)據(jù) (Deleting data from IndexedDB)
Deleting the database, an object store and data
刪除數(shù)據(jù)庫,對象存儲和數(shù)據(jù)
刪除整個IndexedDB數(shù)據(jù)庫 (Delete an entire IndexedDB database)
const dbName = 'mydbname' await deleteDB(dbName)刪除對象存儲中的數(shù)據(jù) (To delete data in an object store)
We use a transaction:
我們使用一筆交易:
(async () => {//...const dbName = 'mydbname'const storeName = 'store1'const version = 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {const store = db.createObjectStore(storeName)}})const tx = await db.transaction(storeName, 'readwrite')const store = await tx.objectStore(storeName)const key = 'Hello again'await store.delete(key)await tx.done })()從先前版本的數(shù)據(jù)庫遷移 (Migrate from previous version of a database)
The third (optional) parameter of the openDB() function is an object that can contain an upgrade function called only if the version number is higher than the current installed database version. In that function body you can upgrade the structure (stores and indexes) of the db:
openDB()函數(shù)的第三個(可選)參數(shù)是一個對象,該對象可以包含僅當(dāng)版本號高于當(dāng)前已安裝的數(shù)據(jù)庫版本時才調(diào)用的upgrade函數(shù)。 在該函數(shù)體中,您可以升級數(shù)據(jù)庫的結(jié)構(gòu)(存儲和索引):
const name = 'mydbname' const version = 1 openDB(name, version, {upgrade(db, oldVersion, newVersion, transaction) {console.log(oldVersion)} })In this callback, you can check from which version the user is updating, and perform some operations accordingly.
在此回調(diào)中,您可以檢查用戶從哪個版本更新,并相應(yīng)地執(zhí)行一些操作。
You can perform a migration from a previous database version using this syntax
您可以使用以下語法從以前的數(shù)據(jù)庫版本執(zhí)行遷移
(async () => {//...const dbName = 'mydbname'const storeName = 'store0'const version = 1const db = await openDB(dbName, version, {upgrade(db, oldVersion, newVersion, transaction) {switch (oldVersion) {case 0: // no db created before// a store introduced in version 1db.createObjectStore('store1')case 1:// a new store in version 2db.createObjectStore('store2', { keyPath: 'name' })}db.createObjectStore(storeName)}}) })()唯一鍵 (Unique keys)
createObjectStore() as you can see in case 1 accepts a second parameter that indicates the index key of the database. This is very useful when you store objects: put() calls don't need a second parameter, but can just take the value (an object) and the key will be mapped to the object property that has that name.
如case 1所示, createObjectStore()接受第二個參數(shù),該參數(shù)指示數(shù)據(jù)庫的索引鍵。 這在存儲對象時非常有用: put()調(diào)用不需要第二個參數(shù),而只需獲取值(一個對象),并且鍵將映射到具有該名稱的對象屬性。
The index gives you a way to retrieve a value later by that specific key, and it must be unique (every item must have a different key)
索引為您提供了稍后通過??該特定鍵檢索值的方法,并且該索引必須唯一(每個項(xiàng)目必須具有不同的鍵)
A key can be set to auto increment, so you don't need to keep track of it on the client code:
可以將鍵設(shè)置為自動遞增,因此您無需在客戶端代碼上跟蹤它:
db.createObjectStore('notes', { autoIncrement: true })Use auto increment if your values do not contain a unique key already (for example, if you collect email addresses without an associated name).
如果您的值尚未包含唯一鍵(例如,如果您收集的電子郵件地址沒有關(guān)聯(lián)的名稱),請使用自動遞增。
檢查商店是否存在 (Check if a store exists)
You can check if an object store already exists by calling the objectStoreNames() method:
您可以通過調(diào)用objectStoreNames()方法來檢查對象存儲是否已存在:
const storeName = 'store1'if (!db.objectStoreNames.contains(storeName)) {db.createObjectStore(storeName) }從IndexedDB刪除 (Deleting from IndexedDB)
Deleting the database, an object store and data
刪除數(shù)據(jù)庫,對象存儲和數(shù)據(jù)
刪除數(shù)據(jù)庫 (Delete a database)
await deleteDB('mydb')刪除對象庫 (Delete an object store)
An object store can only be deleted in the callback when opening a db, and that callback is only called if you specify a version higher than the one currently installed:
僅在打開數(shù)據(jù)庫時才能在回調(diào)中刪除對象存儲,并且僅當(dāng)您指定的版本高于當(dāng)前安裝的版本時,才調(diào)用該回調(diào):
const db = await openDB('dogsdb', 2, {upgrade(db, oldVersion, newVersion, transaction) {switch (oldVersion) {case 0: // no db created before// a store introduced in version 1db.createObjectStore('store1')case 1:// delete the old store in version 2, create a new onedb.deleteObjectStore('store1')db.createObjectStore('store2')}} })要刪除對象存儲中的數(shù)據(jù),請使用事務(wù) (To delete data in an object store use a transaction)
const key = 232 //a random keyconst db = await openDB(/*...*/) const tx = await db.transaction('store', 'readwrite') const store = await tx.objectStore('store') await store.delete(key) await tx.complete還有更多! (There's more!)
These are just the basics. I didn't talk about cursors and more advanced stuff. There's more to IndexedDB but I hope this gives you a head start.
這些只是基礎(chǔ)知識。 我沒有談?wù)撚螛?biāo)和更高級的內(nèi)容。 IndexedDB還有更多功能,但我希望這能為您提供一個開端。
Interested in learning JavaScript? Get my JavaScript book at jshandbook.com
有興趣學(xué)習(xí)JavaScript嗎? 在jshandbook.com上獲取我JavaScript書
翻譯自: https://www.freecodecamp.org/news/a-quick-but-complete-guide-to-indexeddb-25f030425501/
瀏覽器快捷鍵指南
總結(jié)
以上是生活随笔為你收集整理的浏览器快捷键指南_快速但完整的IndexedDB指南以及在浏览器中存储数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到鬼亲我是什么意思
- 下一篇: 响应式网站设计_通过这个免费的四小时课程