如果api的响应是JSON或类似的数据文件,那么可以将JSON作为字符串存储在indexDB中,或者根据需要进行操作。
//JSONfile is the response from your api.
var JSONstring = JSON.stringify(JSONfile)
// Storing JSON as string in indexDB
var dbPromise = idb.open('JSON-db', 1, function (upgradeDB) {
var keyValStore = upgradeDB.createObjectStore('JSONs')
keyValStore.put(JSONstring, 'samples')
})
//provide better key name so that you can retrieve it easily from indexDB
return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
.then((resp) => {
resp.blob()
.then((blob) => {
return db.set(prefetchThisUrl, blob);
});
});
然后,您可以在需要时从indexDB获取信息。为了更好地理解从indexDB存储和检索blob,您可以访问以下站点:
https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/
dbPromise.then(function (db) {
var tx = db.transaction('JSONs')
var keyValStore = tx.objectStore('JSONs')
return keyValStore.get('samples')
}).then(function (val) {
var JSONobject = JSON.parse(val)}