if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
// Registration was successful
console.log('Registered!');
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('service worker is not supported');
}
</script>
// Add the script to your 'index.html' and ...
<script>
(function() {
if("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js", {scope: '/'})
.then(() => console.log("Service Worker registered successfully."))
.catch(error => console.log("Service Worker registration failed:", error));
}
})();
</script>
// don't forget that works only in 'https://' or 'localhost:port' mode so
// if you don't run any server like express.js then install:
// "webpack-dev-server" from npm and add the following line to your package.json
// "scripts: { "start:dev": "webpack-dev-server" }
// npm run start:dev
// it will run your app in 'localhost:8080'
import { register } from 'register-service-worker'
register('/service-worker.js', {
registrationOptions: { scope: './' },
ready (registration) {
console.log('Service worker is active.')
},
registered (registration) {
console.log('Service worker has been registered.')
},
cached (registration) {
console.log('Content has been cached for offline use.')
},
updatefound (registration) {
console.log('New content is downloading.')
},
updated (registration) {
console.log('New content is available; please refresh.')
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
// index.html
window.addEventListener('load', function () {
navigator
.serviceWorker
.register('/service-worker.js');
});