Giter Club home page Giter Club logo

service-worker-updater's Introduction

NPM Contributor Covenant Test Coverage BundlePhobia Minified Size BundlePhobia Minzipped Size BundlePhobia Dependency Count BundlePhobia Tree-shaking support Monthly Downloads Dependabot Active DeepSource

@3m1/service-worker-updater

Manage Create React App's Service Worker update

If you have opted-in for the register callback of serviceWorkerRegistration in the index.js of the PWA version of Create React APP, you probably want to allow your users to update the application once a new service worker has been detected.

How it works

Usually, browsers check for a new service worker version of a PWA every few days, or whenever the user reloads the page. But reloading the page does not necessarily updates the service worker. As the code managing the service worker is usually outside the React components tree, the message of a new service worker detected needs to be passed through another mechanism than props or contexts. Here, we use an event triggered over document, which will previously have been added a listener. The component that adds the listener is inside the React's components tree, and receives and saves the resgistration object for later use in the onLoadNewServiceWorkerAccept callback.

Install

NPM

npm install --save @3m1/service-worker-updater

Yarn

yarn add @3m1/service-worker-updater

Usage

This library is composed by 2 parts:

onServiceWorkerUpdate

Callback to be added to the serviceWorkerRegistration.register call on your index.js. This step is mandatory, or the message will not arrive to your inner component.

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorkerRegistration from './serviceWorkerRegistration'
import { onServiceWorkerUpdate } from '@3m1/service-worker-updater'

// Render the App
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.register({
  onUpdate: onServiceWorkerUpdate
})

// ...

If you are already using the onUpdate callback, you need to add this callback in there:

serviceWorkerRegistration.register({
  onUpdate: (registration) => {
    // Your code goes here
    // ...
    // Then, call this callback:
    onServiceWorkerUpdate(registration)
  }
})

withServiceWorkerUpdater

HOC to wrap a component which will receive 2 extra props:

  • newServiceWorkerDetected: boolean indicating if a new version of the service worker has been detected. If true, you should offer the user some way to update the app.
  • onLoadNewServiceWorkerAccept: a callback which needs to be called once the user accepts to update to the new Service Worker. You choose what actions needs to be taken by the user to update the service worker (a button, a link, a countdown, ...). During its execution, the page will be reloaded in order to use the newly activated service worker. WARNING! Make sure all unsaved changes are saved before executing it.
import React from 'react'
import {
  withServiceWorkerUpdater,
  ServiceWorkerUpdaterProps
} from '@3m1/service-worker-updater'

const Updater = (props: ServiceWorkerUpdaterProps) => {
  const { newServiceWorkerDetected, onLoadNewServiceWorkerAccept } = props
  return newServiceWorkerDetected ? (
    <>
      New version detected.
      <button onClick={onLoadNewServiceWorkerAccept}>Update!</button>
    </>
  ) : null // If no update is available, render nothing
}

export default withServiceWorkerUpdater(Updater)

For non Typescript projects, use the following snippet:

import React from 'react'
import { withServiceWorkerUpdater } from '@3m1/service-worker-updater'

const Updater = (props) => {
  const { newServiceWorkerDetected, onLoadNewServiceWorkerAccept } = props
  return newServiceWorkerDetected ? (
    <>
      New version detected.
      <button onClick={onLoadNewServiceWorkerAccept}>Update!</button>
    </>
  ) : null // If no update is available, render nothing
}

export default withServiceWorkerUpdater(Updater)

The message sent to the service worker is {type: 'SKIP_WAITING'}, which is the one the PWA version of Create React APP expects in order to launch its self.skipWaiting() method. If you have a different service worker configuration, you can change it here using the second optional argument:

export default withServiceWorkerUpdater(Updater, {
  message: { myCustomType: 'SKIP_WAITING' }
})

Just before reloading the page, 'Controller loaded' will be logged with console.log. If you want to change it, do it so:

export default withServiceWorkerUpdater(Updater, {
  log: () => console.warn('App updated!')
})

Persistence

When a new service worker is detected an event is fired. If the app is refreshed, the event is not fired again so you'll no longer be able to notify users about service worker updates. This package provides a solution to that in the form of a PersistenceService.

The persistence service is injected into the component and handles persisting the state after refresh. The package comes with a default persistence service based on local storage. It can be used thus:

import { LocalStoragePersistenceService } from '@3m1/service-worker-updater'

const Updater = () => {
  /* Your updater component code */
}

export default withServiceWorkerUpdater(Updater, {
  persistenceService: new LocalStoragePersistenceService('myApp')
})

You can define your own persistence layer based on other mechanisms by adhering to the PersistenceService interface:

import { PersistenceService } from '@3m1/service-worker-updater'

class YourPersistenceService implements PersistenceService {
  setUpdateIsNeeded(): void {}

  clear(): void {}

  isUpdateNeeded(): boolean {
    return false
  }
}

πŸ† Thanks to

See also

  • React Service Worker: A headless React component that wraps around the Navigator Service Worker API to manage your service workers. Inspired by Create React App's service worker registration script.
  • Service Worker Updater - React Hook & HOC: This package provides React hook and HOC to check for service worker updates.
  • @loopmode/cra-workbox-refresh: Helper for create-react-app v2 apps that use the workbox service worker. Displays a UI that informs the user about updates and recommends a page refresh.

License

GPL-3.0-or-later Β© github.com/emibcn

service-worker-updater's People

Contributors

aeharding avatar chrisharrison avatar deepsource-autofix[bot] avatar deepsourcebot avatar dependabot[bot] avatar emibcn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

service-worker-updater's Issues

Typescript support

Hello! Thanks for this great project.

I was just wondering - would you be open to converting this project to Typescript? If so, I'd be willing to make a PR for it. πŸ™‚

Question: persistent update notification

The newServiceWorkerDetected returns true when an update is detected. But if you refresh the app before applying the update, newServiceWorkerDetected returns false and doesn't return true again. So essentially it's a one time chance to update, if you miss it, that's it!

Is this expected behaviour? And would you have an elegant solution to that?

My naΓ―ve solution at this stage is to have the component write something to a persistent store (local storage?) so upon refresh the fact that the app needs an update is still in state and to continue showing the update component. After the update happens (after calling onLoadNewServiceWorkerAccept) that persisted value would be removed.

ServiceWorker can't be updated after reload

Using the new localStoragePersistenceService:

  • Load the page
  • Generate new ServiceWorker version
  • Get the browser detect it and put it into waiting state
  • The new service worker is detected by the app
  • Reload the page
  • The persistence service allows the app to knows that it still have an awaiting ServiceWorker
  • Clicking on the update button leads to registration not found

`onLoadNewServiceWorkerAccept` triggers nothing, when one tab was already refreshed

First of all thanks for an excellent piece of work and such a time-saving package to deal with the whole PWA update situation πŸŽ‰ .

I am using this library at one of my applications and I am running into the scenario explained below:

  • when the user has multiple tabs open
    • and onLoadNewServiceWorkerAccept is triggered at one of them
  • it reloads that given tab
    • and the notification stays visible at all other tabs
  • when a user clicks the reload button ( triggering onLoadNewServiceWorkerAccept ) at another tab
  • it does nothing (no reload, no console log)

Am I doing something wrong, or is that expected behavior caused by some limitation I am not aware of?

My UpdateNotification code:

import {
  withServiceWorkerUpdater,
  ServiceWorkerUpdaterProps,
  LocalStoragePersistenceService
} from '@3m1/service-worker-updater'

const UpdateNotification = ({
  newServiceWorkerDetected,
  onLoadNewServiceWorkerAccept
}: ServiceWorkerUpdaterProps) => {
  return newServiceWorkerDetected ? (
    <React.Fragment>
      New version detected.
      <button
        onClick={() => onLoadNewServiceWorkerAccept}
      >
        Update!
      </button>
    </React.Fragment>
  ) : null
}

UpdateNotification.displayName = 'UpdateNotification'
export default withServiceWorkerUpdater(UpdateNotification, {
  persistenceService: new LocalStoragePersistenceService('app-name')
})

Testing at chrome: 98.0.4758.109

Thanks for your time πŸ™‡ !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.