因此,在获取事件期间,我必须捕获所有数据并将其存储在索引数据库中。如果我尝试下面的代码,我会得到这样的错误:
DOMException:未能在"IDBObjectStore"上执行"put":未能克隆响应对象。
我想做什么?
- 将我的所有响应存储在indexdb中
- 能够从中获取数据,以防我从索引数据库脱机
- 如果我的数据库中没有数据,则回退到html页面
self.addEventListener("fetch", (event) => {
event.respondWith(
new Promise((resolve,reject) => {
if (navigator.onLine) {
return fetch(event.request).then((response) => {
dbRequest = indexedDB.open("CacheDB", 1);
dbRequest.onupgradeneeded = function (e) {
const db = e.target.result;
if (!db.objectStoreNames.contains("CacheStore")) {
db.createObjectStore("CacheStore");
}
};
dbRequest.onsuccess = function (e) {
const db = e.target.result;
const tx = db.transaction("CacheStore", "readwrite");
const store = tx.objectStore("CacheStore");
console.log(response,event);
try
{
const request = store.put(**response.clone()**`enter code here`);
console.log("I am here")
request.onsuccess = function (e) {
console.log("Successfully cached!!");
resolve(response);
};
request.onerror = function (e) {
console.log("Error occures while storing =>", e);
};
}
catch(err)
{
console.log("err =>",err);
resolve(response);
}
};
dbRequest.onerror = function (e) {
console.log("Error occured while creating DB =>", e);
};
console.log("sending response");
});
} else {
const dbRequest = indexedDB.open("CacheDB", 1);
dbRequest.onsuccess = function (e) {
const db = e.target.result;
const tx = db.transaction("CacheStore", "readwrite");
const store = tx.objectStore("CacheStore");
const request = store.get(event.request.url);
request.onsuccess = function (e) {
console.log("db cahce.. =>", e);
return request.result[0];
};
request.onerror = function (e) {
console.log("Error occures while getting =>", e);
};
};
}
})
);
});
当对象存储在Indexed DB中时,它们被序列化,这基本上是过去被称为"结构化克隆";算法,如下所述:https://html.spec.whatwg.org/multipage/structured-data.html#safe-通过结构化数据
这个错误告诉你Response
对象不能被克隆(序列化/反序列化(——你也可以用下面的代码得到这个错误:
window.postMessage(new Response)
这意味着CCD_ 2对象不支持序列化。要在IndexedDB中存储postMessage()
或Response
,您需要将要序列化的属性提取到可以序列化的对象中。例如,作为Blob
保持报头和响应主体的普通JS对象