user3769778
user3769778

Reputation: 967

Do Service worker do not serves content if fetch API is used?

I have created a service worker to work as a proxy for a particular url. And wanted to serve all request to that url from my service worker.

For example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        (async()=>{
            try{
                if("serviceWorker" in navigator){
                const reg = await navigator.serviceWorker.register("./sw.js",{scope: "./my"});
                console.log("Service worker registered");
                }
            }catch(e){
                console.error("Service worker failed to register");
                console.error(e);
            }
        })()
    </script>
</body>
</html>

And sw.js

self.addEventListener("install",(e)=>{
    console.log("my sw installed");
})

self.addEventListener("fetch",(e)=>{
    const url = new URL(e.request.url).pathname;
    console.log(url);
    if(url === "/my/hello"){
        e.respondWith(new Response("hello world",{status: 200}));
    }else{
        e.respondWith(new Response("Hi there, page not found",{status: 200}));
    }
})

When we run this code in browser with help of some server. If I type http://127.0.0.1:8000/my/hello in the browser url , it gives me hello world.

Now go back to http://127.0.0.1:8000/ and make a fetch request from script or browser's console.

(async()=>{
const res = await fetch("/my/hello");
console.log(await res.text())
})()

I get not found. Do fetch api will directly make call to server and by-pass service worker ?

Upvotes: 0

Views: 901

Answers (1)

Vimal Patel
Vimal Patel

Reputation: 3055

No, if your service worker is up and running then all the request which comes under its scope will pass through fetch event handler irrespective of from where it is originated. Scope does not mean all the request which comes under that will be intercepted. It means all the request which originated from that scope will be intercepted.

In your case your service worker scope is under scope /my/ thats mean all the request which originated under that scope will be intercepted.

The reason it is not working (when you are hitting the url from root) is that your scope does not come under that. If you want to make it work in that case also, change your service worker scope to root i.e / or remove the scope property while registration.

Let me know if things are still not clear.

Upvotes: 2

Related Questions