Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - Service Worker - store is not defined

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...