I hope the question has not been asked too many times. So, I wanted to create my own service worker file, in my React project. I called it 'sw.js' and put it in the src/ folder, the same folder that contains the 'index.js' file which contains all the jsx. The architecture of the React Project is :
- node_modules -public -src -----index.js -----sw.js -package -package-lock -README
As soon as the page load, the service worker should register in the browser. However , on Firefox, I have the following error : "Failed to register/update a ServiceWorker for scope ‘http://localhost:3000/’: Bad Content-Type of ‘text/html’ received for script ‘http://localhost:3000/sw.js’. Must be a JavaScript MIME type."
"Service Worker Error DOMException: "The operation is insecure.""
I know that the error does not com from the code of registering the service worker itself, because it worked on a standard project with no react
here is the code registering the service worker in index.js :
render() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('/sw.js')
.then(swReg => {
console.log('Service Worker is registered', swReg);
this.setState({ swReg : swReg } )
// TODO 3.3a - call the initializeUI() function
})
.catch(err => {
console.error('Service Worker Error', err);
});
});
}
As you can see, I put it in the render method of my main React component
state