Gatsby: Access navigator.serviceWorker only via `localhost` and `https://`

Created on 2 Jan 2018  Â·  4Comments  Â·  Source: gatsbyjs/gatsby

Description

Please add a code guard to app.js to avoid throwing exceptions while develping with gatsby develop on non-localhost and non-https domains.

Please see https://goo.gl/Y0ZkNV for details.

Environment

Gatsby version: 1.9.149
Node.js version: v7.0.0
Operating System: MacOS 10.11.3

File contents (if changed):

gatsby-config.js:
package.json:
gatsby-node.js:
gatsby-browser.js:
gatsby-ssr.js:

Actual result

https://gist.github.com/denster/729654499864f2edb2003ca4ffa58d5a

Expected behavior

No exceptions thrown.

What should happen?

Steps to reproduce

1. Run gatsby develop

2. Open browser to http://example-domain.local:8000/

3. The above exception will occur because navigator.serviceWorkers is only safe to access from localhost and https:// URLs.

The issue is with app.js (which is written out to .cache/app.js):

  if (`serviceWorker` in navigator) {
    navigator.serviceWorker.getRegistrations().then(registrations => {
      for (let registration of registrations) {
        registration.unregister()
      }
    })
  }

The access of serviceWorker in the case of a non-localhost and non-https domain causes an exception in Chrome (see gist above for full stacktrace):

login:1 Uncaught (in promise) DOMException: Only secure origins are allowed (see: https://goo.gl/Y0ZkNV).

Proposed solution

Add a guard to the above code to check for either of:
a) Using:localhost
b) Using https

Most helpful comment

@busticated's fix merged 🎉

All 4 comments

Sounds like a great suggestion! Could you put together a PR fixing this?

Easiest fix would be to change that if statement to:

if (location.protocol == 'https:' && 'serviceWorker' in navigator) {

That way, even if localhost has service workers running, it will clear them. It works locally, but haven't had time to submit a PR yet.

hope ya'll don't mind i took a crack at this since it's something of a blocker for me. hope it helps!

@busticated's fix merged 🎉

Was this page helpful?
0 / 5 - 0 ratings

Related issues

theduke picture theduke  Â·  3Comments

Oppenheimer1 picture Oppenheimer1  Â·  3Comments

kalinchernev picture kalinchernev  Â·  3Comments

mikestopcontinues picture mikestopcontinues  Â·  3Comments

dustinhorton picture dustinhorton  Â·  3Comments