Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Service Worker Sample for posting messages from a page that isn't controlled #94

Closed
wants to merge 2 commits into from

Conversation

TalAter
Copy link
Contributor

@TalAter TalAter commented Mar 13, 2015

This new code sample shows how a page that has just registered a Service Worker, but is still not being controlled by it, can use the ServiceWorkerRegistration object to post messages to the new Service Worker.

It also shows how to detect whether to use this method, or good old fashioned (old?) navigator.serviceWorker.controller.

All the samples provided so far (and all the tutorials I saw) only began communication using postMessage after the page was refreshed... so finding this little gem in the Service Worker spec was a lifesaver.

@jpmedley
Copy link
Contributor

This looks good, but I have a few concerns. If the install handler calls event.waitUntil(), the message will be blocked. Maybe your explanation should point this out.

Also, if you're trying to get the jump on the install process, it seems like you might be setting yourself up for a race condition. What's the use case for this trick?

@TalAter
Copy link
Contributor Author

TalAter commented Mar 13, 2015

Thanks @jpmedley.

I just tried this out with very long installation process inside an event.waitUntil() and couldn't see how the message could be blocked. I'm using ServiceWorkerRegistration which is only returned when the promise from registering the service worker completes.

navigator.serviceWorker.register('sw.js').then(function(registration) {
  // registration contains an installed Service Worker here
})

Is there a way that I'm missing which might cause a race condition or the message to be blocked?

As for a use case, there are many. The one I'm looking at right now is a script that saves data into the cache. The data to save is present in the page, and not in the service worker code.

This means that without this method, if I want to send the data to the Service Worker so it will cache it, I need to wait until the second time the user visits this page, and the Service Worker is in control of the page.

Here's some code that uses this trick to allow me to place messages into the cache when the user first visits the page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants