https://github.com/bennypowers/service-worker
Custom Element for declaratively adding a service worker with "Click To Update" prompt and optional auto-install.
https://github.com/bennypowers/service-worker
customelements hacktoberfest service-worker sw-precache webcomponents workbox
Last synced: about 1 year ago
JSON representation
Custom Element for declaratively adding a service worker with "Click To Update" prompt and optional auto-install.
- Host: GitHub
- URL: https://github.com/bennypowers/service-worker
- Owner: bennypowers
- License: isc
- Created: 2018-01-14T11:57:28.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2023-01-24T17:50:57.000Z (over 3 years ago)
- Last Synced: 2025-03-28T22:35:26.963Z (about 1 year ago)
- Topics: customelements, hacktoberfest, service-worker, sw-precache, webcomponents, workbox
- Language: TypeScript
- Homepage:
- Size: 772 KB
- Stars: 23
- Watchers: 1
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Funding: .github/FUNDING.yml
- License: LICENSE.md
Awesome Lists containing this project
README
[](https://npm.im/@power-elements/service-worker)
[](https://www.webcomponents.org/element/bennypowers/service-worker)
[](https://github.com/bennypowers/service-worker/actions?query=workflow%3Atest)
[](https://codeclimate.com/github/bennypowers/service-worker/test_coverage)
[](https://codeclimate.com/github/bennypowers/service-worker/maintainability)
[](https://www.codementor.io/bennyp?utm_source=github&utm_medium=button&utm_term=bennyp&utm_campaign=github)
💕 Proudly built using [open-wc](https://open-wc.org) and [Modern Web](https://github.com/modernweb-dev/web) Tools.
# service-worker
Custom Element for declaratively adding a service worker with optional auto-update.
## Example
```html
```
## Properties
| Property | Attribute | Type | Default | Description |
|-----------------|-----------------|-------------------------|----------------------|--------------------------------------------------|
| `autoReload` | `auto-reload` | `boolean` | false | If true, when updates are found, the page will automatically
reload, so long as the user has not yet interacted with it. |
| `channelName` | `channel-name` | `string \| null` | "service-worker" | Channel name for communicating with the service worker. |
| `error` | `error` | `Error` | | Error state of the service-worker registration |
| `installed` | `installed` | `boolean` | false | True when the service worker is installed. |
| `path` | `path` | `string` | "/service-worker.js" | Path to the service worker script. |
| `scope` | `scope` | `string` | "/" | Scope for the service worker. |
| `serviceWorker` | | `ServiceWorker \| null` | null | A reference to the service worker instance. |
| `updateAction` | `update-action` | `string \| null` | "skipWaiting" | String passed to serviceWorker which triggers self.skipWaiting().
String will be passed in message.action. |
## Methods
| Method | Type | Description |
|-------------------------|--------------------------------------------------|--------------------------------------------------|
| `#onError` | `(error: Error): Error` | Sets the error property |
| `#onRegistration` | `(reg: ServiceWorkerRegistration): ServiceWorkerRegistration` | |
| `#refresh` | `(): void` | |
| `#track` | `(serviceWorker: ServiceWorker): ServiceWorker` | Listen for changes on a new worker, notify when installed. 🍞 |
| `#update` | `(serviceWorker: ServiceWorker): ServiceWorker` | When 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> \| undefined): Promise` | Registers a service worker, and prompts to update as needed |
## Events
| Event | Type | Description |
|-----------|-----------------------------|--------------------------------------------------|
| `change` | `ServiceWorkerChangeEvent` | When the service worker changes |
| `error` | `ServiceWorkerErrorEvent` | When an error occurs |
| `message` | `ServiceWorkerMessageEvent` | When a message is received on the broadcast channel |
## Updating the Service Worker.
When an updated service worker is detected, `` 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()`:
```js
self.addEventListener('message', event => {
switch (event.data.action) {
case 'skipWaiting': return self.skipWaiting();
}
});
```
If `auto-reload` is set, `` 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.
```js
const dialogTemplate = document.createElement('template');
dialogTemplate.innerHTML = `
New Version Available!
Reload the Page?
OK
Cancel
`;
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](https://github.com/GoogleChromeLabs/sw-precache#skipwaiting-boolean) to generate your SW, it will automatically skip waiting on reload, unless you specify otherwise in `sw-precache-config.js`
### Workbox
[Workbox](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-sw.WorkboxSW) offers a similar feature, although you must opt in when constructing the workbox instance.
#### Directly in service-worker.js
```js
// service-worker.js
const workboxSW = new WorkboxSW({
skipWaiting: true,
});
```
#### Workbox CLI
```js
// workbox-config.js
module.exports = {
// ...
skipWaiting: true,
};
```
#### Rollup
```js
// rollup.config.js
import { generateSW } from 'rollup-plugin-workbox';
export default {
// ...
// use workbox-config.js as above
plugins: [generateSW(require('./workbox-config.js'))]
}
```
#### Webpack
```js
// webpack.config.js
const workboxPlugin = require('workbox-webpack-plugin');
plugins: [
new workboxPlugin({
skipWaiting: true,
}),
];
```
#### Gulp
```js
// gulpfile.js
const workbox = require('workbox-build');
gulp.task('generate-service-worker', () => {
workbox.generateSW({
skipWaiting: true,
});
});
```