Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially registering the service worker. However, upon refreshing the page, it functions perfectly fine and I am baffled by this behavior. Here is the structure of my app's public folder:

/public
    /assets
    /icons
    manifest.json
    service-worker.js
    service-worker-registration.js

manifest.js:

{
  "name": "FakeHulu",
  "short_name": "FakeHulu",
  "description": "My Own version of Hulu",
  "icons": [
    {
      "src": "/icons/manifest-icon-192.maskable.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "any"
    }, ...

  ],
  "theme_color": "#ffffff",
  "background_color": "#ffffff",
  "start_url": "/",
  "display": "fullscreen",
  "orientation": "portrait"
}

service-worker-registration.js:

if("serviceWorker" in navigator){
    window.navigator.serviceWorker.register("/service-worker.js", { scope: '/' }).then(sw => console.log("serviceWorker Supported and register"))
}

service-worker.js:

self.addEventListener("install" , evt => {
    evt.waitUntil(caches.open("main_cache").then(cache => cache.addAll(["/", "/something"])));

    self.skipWaiting();
});

self.addEventListener("activate" , evt => {
    console.log(evt);
    clients.claim();
});

self.addEventListener("fetch" , evt => {
    console.log(evt);
});

Answer №1

When you first visit the site, the sequence of actions is as follows:

  1. Download the client page.
  2. Locate the software registration in the client page and download it.
  3. Install the service worker.

It's important to note that there is no fetch() handler running at this point because the service worker has not been fully installed yet.

Upon reloading the page, the process occurs in this order:

  1. Refresh the page.
  2. The existing service worker's Fetch() handler intercepts the request and determines whether to fetch the requested resource from a local cache or the network.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why are two vertical scrolls appearing on the screen simultaneously?

I utilized this method to hide the body scrollbar initially and then display it upon clicking a link: $('body').css('overflow', 'hidden'); $('#site').click(function(e) { $('#wrapper').remove(); $(& ...

Getting an undefined error value in the ionic overlay side menu - what could be causing this issue?

My current challenge involves displaying the overlay side menu. I have written code to achieve this, adding a menu icon in the header that opens the overlay side menu when clicked, and closes it when clicked outside. However, I encountered an issue where ...

Display every even number within the keys of objects that have values ending with an odd number

I need a way to print all even values that are paired with odd values in the object keys, but my code only works for arr1, arr3, and arr5. Can someone help me adjust the 'let oddArr' method (maybe using a loop) so that it will work for any array ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Discover the paths to locate all keys within an object that correspond to a specified string

I need help creating a function in plain JavaScript that can find all paths to keys with a specific name in an object. The object may have repeated key names at different depths. Here is an example: const obj = { stuff: { A: 'text' ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

Encountering issues retrieving information from Form utilizing FormData

Working on a 'edit profile' feature within a dashboard using Next.js, Node.js & MongoDB. Note: If you are interested only in the issue, feel free to skip to the backend part. Frontend Firstly, let's discuss the Frontend part. Utilizing ...

Using async-await to handle an array of promises with the map method

I have come across several discussions on the same error but none of them solved my issue. Here is the code I wrote: const userOrganizationGroups = (organizationGroupsList) => { if (Array.isArray(organizationGroupsList) && organizationGroupsLi ...

Using JSON to insert an array into an object with identical key name

var arr = ['1', '2', '3'] var part = {} var partContents = [] arr.map(function(i){ partContents.push({ obj: i }) part['text'] = partContents }) console.log(part); Is there a way to create separate arrays with ...

Removing an unnecessary DIV element from an HTML Document

I have been working on a News application and am utilizing a web product to fetch News Headlines. When I request a NewsHeadline, the product sends back an HTML Code containing the News Headline. <div class="mydiv"> <script type="text/javascript ...

Using JavaScript to browse and filter by category

After spending some time working on a search function, I received some assistance from Tim Down who provided me with a simple code to search for specific text within a page. Now, my goal is to modify the code to enable searching by category. I have struct ...

Is it possible to obtain the parameters using an empty object with the getStaticPaths function?

Within the getStaticPaths function, a path is returned with params postId:1. If additional params like postId: 2 or postId: 3 are included, they will also be statically generated. Is my understanding correct? Is there a way to avoid loading any post based ...

Decoding the Blueprint of Easel in JavaScript

Recently, I came across a fantastic API that promises to simplify working with CANVAS by allowing easy selection and modification of individual elements within the canvas. This API is known as EaselJS, and you can find the documentation here. While I foun ...

Android browser experiences a sudden surge of unexpected data influx

I am facing an issue with my application where it maps an array from the state. The array should ideally only contain 6 sets of data, as limited by the backend. However, sometimes it spikes and displays data that is not supposed to be there or shows old da ...

What advantages does incorporating "function() 'use strict'" into each individual file provide?

As I dive into revamping an older AngularJS 1.3 project, one striking observation is the consistent pattern of starting each AngularJS code file with: (function () { 'use strict'; angular.module('app').factory('Employees', ...

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Ways to resolve the issue of data-bs-target not functioning properly in Bootstrap version 5

While viewing the Job screen in the following image, I attempted to click on "Personal," but it remained stuck on the Job screen. ...

Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure: _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: ...

Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it' ...

I am experiencing an issue with environment variables not appearing in my Context component on Next.js. Should I adjust the Next.js configuration or set up the Context to properly utilize the variables?

Why are Environment Variables working on every component inside /pages but not in my Context component in Next.js? Do I need to do some configuration in Next.js for this? (Note: The Shopcontext.tsx file is using a class component that I obtained from a tu ...