I am creating a progressive web application (pwa) and try to register service worker to test offline feature. The folder structure is like below:
-- views
-- index.pug
-- sw.js
-- public
-- js
-- main.js
-- index.js
index.js file is server file, main.js is the file that being link in each .pug file. I embedded the service worker register code in, the code is like following
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('./sw.js').then(function(registration) {
// Registration was successful
console.log('Service Worker registration successful with scope: ', registration.scope);
// console.log('Service Worker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
The 404 error keeps pop up in localhost also the deployed URL which I have no clue why, how to solve this?
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
Thanks
Solutions (UPDATE) -
Include app.use('/', routes)
,or wherever the service-worker file at into index.js file.
Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script it is most probably the placement of the firebase-messaging-sw.js file which is wrong here.
[Service Worker Installation] Installing service worker failed TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. · Issue #490 · OneSignal/OneSignal-Website-SDK · GitHub Sign up for free to join this conversation on GitHub . Already have an account? Sign in to comment
If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker.
The service worker URL is fetched and registered via serviceWorkerContainer.register (). If successful, the service worker is executed in a ServiceWorkerGlobalScope; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.
you could use the full url path for the registration for example:
navigator.serviceWorker.register('ScriptsFolder/subFolder/sw.js')
The only way I have found to solve the TypeError issue when starting a nodejs service worker is to put the service worker script in the root directory of your application, in my case the root of my Amazon EC2 web server.
Wish the error message was more descriptive, TypeError is not terribly helpful. But this fix worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With