要在中使用indexdb的代码示例
firebase-messaging-sw.js
messaging.setBackgroundMessageHandler(payload => {
try {
function logerr(err) {
console.log('Database erroor: ',err);
}
function connectDB(f) {
const request = exports.indexedDB.open('lone', 1);
request.onerror = logerr;
request.onsuccess = function() {
f(request.result);
};
request.onupgradeneeded = function(e) {
e.currentTarget.result.createObjectStore('Table1', { keyPath: 'ssn' });
connectDB(f);
};
}
connectDB(db => {
const transition = db.transaction(['Table1'], 'readwrite');
const objectStore = transition.objectStore('data');
const customerData = {
ssn: '444-44-4444',
payload: payload.data.payload,
};
const objectStoreRequest = objectStore.add(customerData);
objectStoreRequest.onerror = logerr;
objectStoreRequest.onsuccess = function() {
return objectStoreRequest.result;
};
});
const notificationTitle = 'Title';
const notificationOptions = {
body: message,
icon: 'favicon.png',
};
return self.registration.showNotification(notificationTitle, notificationOptions);
} catch (e) {
console.log('error', e);
}
});
})(this);