0

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

3
  • Doesn't make sense doing this in render() and you should never directly assign values to state Commented Jul 10, 2019 at 12:50
  • I have replaced the this.state by this.setState, and I still have the same error. Where can I put my script for registering service workers if I want it to be done automatically ? Commented Jul 10, 2019 at 12:54
  • Possible duplicate of this question stackoverflow.com/questions/49566059/… Commented Jul 11, 2019 at 5:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.