I have three javascript files:
store.js
which encapsulates IndexedDB and uses idb.js
var store = {
db: null,
TABLE_PENDING: 'pending',
init: function() {
if (store.db) { return Promise.resolve(store.db); }
return idb.open('messages', 1, function(upgradeDb) {
upgradeDb.createObjectStore(store.TABLE_PENDING, { autoIncrement : true, keyPath: 'id' });
}).then(function(db) {
return store.db = db;
});
},
pending: function(mode) {
return store.init().then(function(db) {
return db.transaction(store.TABLE_PENDING, mode).objectStore(store.TABLE_PENDING);
})
}
}
register-sw.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js', {scope: './'})
.then((reg) => {
// registration worked
console.log('Service Worker Registration succeeded. Scope is ' + reg.scope);
if ('sync' in reg) {
return reg.sync.register(store.TABLE_PENDING);
}
}).catch((error) => {
// registration failed
console.log('Service Worker Registration failed with ' + error);
});
}
and sw.js
self.addEventListener('sync', function(event) {
event.waitUntil(
store.pending('readonly').then(function(outbox) {
return outbox.getAll();
}).then(function(messages) {
return Promise.all(messages.map(function(message) {
console.write("Sync Invoked: Got stored message : " + sms.message);
return message;
}))
}).catch(function(err) {
console.error(err);
})
);
});
and finally, the HTML file, where these (and idb.js
) are included as under in head
tag
<script src="./js/idb.js"></script>
<script type="text/javascript" src="./js/store.js"></script>
<script type="text/javascript" src="./sw.js"></script>
<script type="text/javascript" src="./register-sw.js"></script>
When I run it on the browser, I get an error in sw.js
store is not defined
This error is not coming in register-sw.js
which also uses store
.
Any clues ?
P.S. I was following example from here
question from:
https://stackoverflow.com/questions/65898715/service-worker-store-is-not-defined 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…