rwjblue / ember-service-worker-project-entagled-registration

MIT License
0 stars 1 forks source link

Issue registering service worker #1

Open piotrpalek opened 8 years ago

piotrpalek commented 8 years ago

Hey, I have an issue with the registration step of ember-service-worker due to this plugin. The error message I've got is: Service Worker registration failed with TypeError: Cannot read property 'postMessage' of null which points to this line in the plugin.

Worth noting is that it only happens when it's a fresh install of the service worker due to hitting hard refresh in Chrome or unregistering the SW manually and refreshing the page normally. Also if I put a breakpoint before hitting the postMessage call and then continue the script the SW registers fine.

It seems that there's an expected gap in time between when the register() call resolves and when the service worker takes control of your page which might be part of the issue if I'm understanding this right? There's also "This property returns null if the request is a force refresh (Shift + refresh) or if there is no active worker" on the navigator.serviceWorker.controller MDN docs.

Anyway I'm trying to understand this and find the proper way to fix it and am unsure if a simple if guarding the postMessage call would be enough, or if there's some way to wait for the SW to actually be active before using it.

ps. I'm currently trying this out on a forked EmberTwiddle which can be looked up here, hopefully it isn't an issue that's just manifesting on my end.

piotrpalek commented 7 years ago

@rwjblue replacing the addSuccessHandler with something like this (quickndirty code):

addSuccessHandler(function(registration) {
  return navigator.serviceWorker.ready
    .then(function() {
      if(navigator.serviceWorker.controller) {
        return sendMessage({ command: 'verify-project-revision', revision: PROJECT_REVISION});
      } else {
        return new Promise(function(resolve, reject) {
          navigator.serviceWorker.oncontrollerchange = function() {
            sendMessage({ command: 'verify-project-revision', revision: PROJECT_REVISION}).then(resolve);
          };
        });
      }
    })
    .catch(function(error) {
      return registration.unregister()
        .then(function() {
          throw error;
        });
    });
});

seems to work, looks like we would need something like a addControllerchangeHandler method for the registration part of ember-service-worker