6.0.0 ā€¢ Published 1 year ago

@power-elements/service-worker v6.0.0

Weekly downloads
4
License
ISC
Repository
-
Last release
1 year ago

Published on npm Published on webcomponents.org Test Status Test Coverage Maintainability Contact me on Codementor

šŸ’• Proudly built using open-wc and Modern Web Tools.

service-worker

Custom Element for declaratively adding a service worker with optional auto-update.

Example

<service-worker id="serviceWorker"
    path="./service-worker.js"
    scope="/muh-data/"
    auto-reload
></service-worker>

Properties

PropertyAttributeTypeDefaultDescription
autoReloadauto-reloadbooleanfalseIf true, when updates are found, the page will automaticallyreload, so long as the user has not yet interacted with it.
channelNamechannel-namestring \| null"service-worker"Channel name for communicating with the service worker.
errorerrorErrorError state of the service-worker registration
installedinstalledbooleanfalseTrue when the service worker is installed.
pathpathstring"/service-worker.js"Path to the service worker script.
scopescopestring"/"Scope for the service worker.
serviceWorkerServiceWorker \| nullnullA reference to the service worker instance.
updateActionupdate-actionstring \| null"skipWaiting"String passed to serviceWorker which triggers self.skipWaiting().String will be passed in message.action.

Methods

MethodTypeDescription
#onError(error: Error): ErrorSets the error property
#onRegistration(reg: ServiceWorkerRegistration): ServiceWorkerRegistration
#refresh(): void
#track(serviceWorker: ServiceWorker): ServiceWorkerListen for changes on a new worker, notify when installed. šŸž
#update(serviceWorker: ServiceWorker): ServiceWorkerWhen an update is found, if user has not yet interacted with the page,reload it for them, otherwise, prompt them to reload šŸ©.
#updateChannelName(): void
#updateConfig(): void
registerServiceWorker(options?: Partial<Pick<ServiceWorkerElement, "path" \| "scope" \| "updateAction">> \| undefined): Promise<void \| ServiceWorkerRegistration>Registers a service worker, and prompts to update as needed

Events

EventTypeDescription
changeServiceWorkerChangeEventWhen the service worker changes
errorServiceWorkerErrorEventWhen an error occurs
messageServiceWorkerMessageEventWhen a message is received on the broadcast channel

Updating the Service Worker.

When an updated service worker is detected, <service-worker> will post a message to the service worker with the contents { action: this.updateAction }. You can customize the name of the passed action by setting the updateAction property or the update-action attribute (they will sync with each other). updateAction is by 'skipWaiting' by default. You can then handle that message in your service worker by running self.skipWaiting():

self.addEventListener('message', event => {
  switch (event.data.action) {
    case 'skipWaiting': return self.skipWaiting();
  }
});

If auto-reload is set, <service-worker> will check if the user has not yet interacted with the app, and if she hasn't, refresh the page by calling location.reload() when the new service-worker is installed. Listen for the service-worker-changed event to display a message to the user when the service worker updates.

const dialogTemplate = document.createElement('template');
dialogTemplate.innerHTML = `
  <dialog>
    <form method="dialog">
      <h1>New Version Available!</h1>
      <p>Reload the Page?</p>
      <menu>
        <button value="confirm">OK</button>
        <button value="cancel">Cancel</button>
      </menu>
    </form>
  </dialog>
`;
document.querySelector('service-worker')
  .addEventListener('service-worker-changed', event => {
    const dialog = dialogTemplate.content.cloneNode(true);
    dialog.addEventListener('close', function({ returnValue }) {
      if (returnValue === 'confirm') location.reload();
    });
    document.body.append(dialog);
    dialog.showModal();
  })

sw-precache

If you are using sw-precache to generate your SW, it will automatically skip waiting on reload, unless you specify otherwise in sw-precache-config.js

Workbox

Workbox offers a similar feature, although you must opt in when constructing the workbox instance.

Directly in service-worker.js

// service-worker.js
const workboxSW = new WorkboxSW({
  skipWaiting: true,
});

Workbox CLI

// workbox-config.js
module.exports = {
  // ...
  skipWaiting: true,
};

Rollup

// rollup.config.js
import { generateSW } from 'rollup-plugin-workbox';
export default {
  // ...
  // use workbox-config.js as above
  plugins: [generateSW(require('./workbox-config.js'))]
}

Webpack

// webpack.config.js
const workboxPlugin = require('workbox-webpack-plugin');

plugins: [
  new workboxPlugin({
    skipWaiting: true,
  }),
];

Gulp

// gulpfile.js
const workbox = require('workbox-build');

gulp.task('generate-service-worker', () => {
  workbox.generateSW({
    skipWaiting: true,
  });
});
6.0.0

1 year ago

5.0.0

4 years ago

4.0.4

4 years ago

4.0.3

4 years ago

4.0.2

4 years ago

4.0.1

4 years ago

4.0.0

4 years ago

3.2.0

5 years ago

3.1.5

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.0

6 years ago

3.0.0

6 years ago

2.0.0

6 years ago

1.4.1

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.0.0

6 years ago