Service worker and other progressive web application helpers
npm install @jsenv/pwaA toolkit to implement progressive web application (PWA) features in your website.
š Add to home screen functionality
š Service worker lifecycle management
š± Display mode detection
š ļø Simple APIs for complex PWA features
- @jsenv/pwa
- Table of Contents
- Installation
- Add to Home Screen
- Usage Example
- API Reference
- addToHomescreen.isAvailable()
- addToHomescreen.listenAvailabilityChange(callback)
- addToHomescreen.prompt()
- displayModeStandalone
- Service Worker
- Usage Example
- API Reference
- createServiceWorkerFacade()
``console`
npm install @jsenv/pwa
Allow users to add your website to their device homescreen, running it in a standalone mode without browser UI.
`html
`
#### addToHomescreen.isAvailable()
Returns a boolean indicating if the "Add to Home Screen" feature is available.
`js
import { addToHomescreen } from "@jsenv/pwa";
if (addToHomescreen.isAvailable()) {
// Enable "Add to Home Screen" button
}
`
The feature is available when the browser has fired a beforeinstallprompt event.
#### addToHomescreen.listenAvailabilityChange(callback)
Registers a callback that will be called whenever the availability of "Add to Home Screen" changes.
`js
import { addToHomescreen } from "@jsenv/pwa";
addToHomescreen.listenAvailabilityChange(() => {
const isAvailable = addToHomescreen.isAvailable();
console.log(
Add to homescreen is now ${isAvailable ? "available" : "unavailable"},`
);
});
#### addToHomescreen.prompt()
Prompts the user to add the website to their home screen. Returns a promise that resolves to a boolean indicating whether the user accepted.
`js
import { addToHomescreen } from "@jsenv/pwa";
button.onclick = async () => {
if (!addToHomescreen.isAvailable()) {
return;
}
const userAccepted = await addToHomescreen.prompt();
if (userAccepted) {
console.log("User added the app to home screen");
} else {
console.log("User declined the add to home screen prompt");
}
};
`
> Important: This must be called inside a user interaction event handler (like click) to work properly.
#### displayModeStandalone
An object to detect if the website is running in standalone mode (added to home screen).
`js
import { displayModeStandalone } from "@jsenv/pwa";
// Check current mode
const isStandalone = displayModeStandalone.get();
console.log(Running in ${isStandalone ? "standalone" : "browser"} mode);
// Listen for mode changes
displayModeStandalone.listen(() => {
if (displayModeStandalone.get()) {
console.log("App is now running in standalone mode");
} else {
console.log("App is now running in browser mode");
}
});
`
Service workers enable offline functionality and background updates for your web application.
`html
``
#### createServiceWorkerFacade()