Tips for resolving the issue of service worker navigating and encountering the error message "This service worker is not the client's active service worker."

I have implemented a service worker for my Quasar PWA to handle FCM web background notifications. The main objective is to manage clicks on foreground and background notifications and direct the user to a specific page on my PWA.

When I receive a notification, there are two scenarios:

Foreground notifications:

  • 1a) If the browser is focused/maximized and the user is already on the PWA tab with the correct page -> no action needed
  • 1b) If the browser is focused/maximized and the user is already on the PWA tab but not on the right page -> I need to redirect to the specific PWA page

Background notifications:

  • 2a) If the browser is not focused or minimized or the user is not on the PWA tab but on the correct page -> focus/maximize the browser or switch to the PWA tab and then no further action required
  • 2b) If the browser is not focused or minimized or the user is not on the PWA tab and on another page -> focus/maximize the browser or switch to the PWA tab and then redirect to the specific PWA page

Everything functions correctly in scenarios 1a, 1b, and 2a. However, I encounter a strange error in scenario 2b: "This service worker is not the client's active service worker".

I have added the following code to the service worker to manage redirection upon clicking on background notifications. The error occurs at the navigate() method.

self.addEventListener('notificationclick', function(event) {
    console.log('notificationclick', event);
    event.notification.close();

    let route = event.notification.data.route ? JSON.parse(event.notification.data.route) : null;
    if(route && route.params && route.params.token) {
      const domain = route.domain;
      const path = '/#/' + route.name + '/' + route.params.token;
      const fullUrl = domain + path

      event.waitUntil(clients.claim().then(() => {
          return clients.matchAll({
            type: 'window',
            includeUncontrolled: true
          })
          .then(clients => clients.filter(client => client.url.indexOf(domain) !== -1))
            .then(matchingClients => {
              if (matchingClients[0]) {
                return matchingClients[0].focus().then(function (client) {
                  client.navigate(path)
                    .then(client => {
                    }).catch(function (e) {
                    console.log(e); --> here I get the error
                  });
                }).catch(function (e) {
                  console.log(e);
                });
              }

              return clients.openWindow(fullUrl);
            })
          })
      );
    }
  });

I have tried searching for this error online but couldn't find any relevant information, making it difficult to understand and resolve. Can anyone offer assistance, please? Thank you

Answer №1

After struggling to make client.navigate(path) work, I decided to use client.postMessage() instead. Despite hours of searching through GitHub and MDN docs, I couldn't find a solution.

To replace client.navigate(path) in your code, try this:

client.postMessage({
  action: 'redirect-from-notificationclick',
  url: path,
})

In your application code, add a listener for this message:

// Listen for messages from the service worker using postMessage()
navigator.serviceWorker.addEventListener('message', (event) => {
  if (!event.data.action) {
    return
  }

  switch (event.data.action) {
    case 'redirect-from-notificationclick':
      window.location.href = event.data.url
      break
    // no default
  }
})

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

The Selenium server is currently operational, however, it is encountering issues while attempting to establish a connection with the

I am currently working on setting up test automation using WebdriverIO. After successfully installing all the necessary packages with selenium-standalone, I encountered an issue when trying to start the server. https://i.sstatic.net/7K1O5.png Upon runnin ...

Is it possible for React and React Router to render the same element twice with different props, creating two elements with identical props?

Currently, I am exploring how to leverage React in conjunction with React Router v4 to display multiple elements. The concept revolves around a component that showcases a list of articles sourced from various websites. Each route corresponds to a distinct ...

Transforming jquery code into Angularjs code

I am currently working on a jQuery method that adds a 'selected' class to table rows and handles click events. Here is the code: $('.niGridTable table tr').addClass('selected').end().click(function (event) { event = ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

Export data from a dynamically generated table to an Excel file with SheetJS

I have been dynamically adding rows to an HTML table and I am trying to save the content of the table into an xlsx file using SheetJs. However, the generated file is currently empty. Is there a way to achieve this when the table content is added in this ...

Clear Redis sorted set scores following zremrangebyscore operation

Currently, I am utilizing a Redis sorted set to maintain values in a specific order. Here is an example: score | data 0 | a 1 | b 2 | c 3 | d There are situations in my application where I need to delete certain entries. For instance, ...

The functionality of Bootstrap "tabs" and "navbar" seems to be malfunctioning within the electron environment

Bootstrap is being loaded using the following code: <script> let $ = require('jquery') ; </script> <script src="./bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script> ...

The route parameters seem to be malfunctioning when using the Google Maps Directions API

Currently, I am attempting to transfer the latitude and longitude of a location from one HTML file to another using the $routeParams feature. In the second HTML file, I utilized the Google Maps directions API to display the directions from the source lati ...

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

The Vaadin JavaScript popup feature functions correctly only on the initial use during each session

I am faced with a situation where my application requires cleanup no matter how the user leaves the page. To achieve this, I am using JavaScript to detect when the user exits the page and display a popup warning them that the current process will be halted ...

Retrieving HTML Content with Ajax

Currently using this script for an assignment in my class. Still learning! The script checks whether a site is down or not. I want to expand this script to display statuses for each website in the table without duplicating the script. Any suggestions on ...

Adding a query parameter to a dynamic route in NextJS

In my NextJS application, I have implemented a language selector that is displayed on every page. The goal is to change the current URL by adding a query parameter lang=en when a new language is selected. The function responsible for updating the URL look ...

Prevent Page Refresh with F5 in Silverlight

Many of the users on my platform are accidentally hitting the F5 key while typing, causing them to lose all their work. I don't want to completely block the ability to refresh the page. I attempted using the following JavaScript solution, however it ...

Easily convert grams to kilograms with just a click of a button using JavaScript

Enter Grams(g): <input type="text" name="grams" id="grams"><br> <br> <button type="button" onclick="kiloConversion()">Convert to Kilogram</button> <p id="conversionResult"></p> ...

How can Three JS and an image be combined to make a custom 3D cookie cutter?

I am currently working on a project that involves extracting the edges of a black and white image. My goal is to then generate a 3D model that highlights the edges of the black shape, extrudes the edges for depth, adds thickness to the walls, and creates ...

Where is the best place to safely integrate admin capabilities in Angular?

In my Angular 7 application, I am looking to introduce some admin functionalities such as user dataset editing. Typically, I like to keep the admin panel separate from the main project and host it on a different domain to enhance security measures. Howeve ...

Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...

Change the object's property names from camel case to sentence case

Consider an array of objects like this: data = [{keyOne: 'value1', keyTwo: 'value2'}, {keyOne: 'value3', keyTwo: 'value4'}]; We need to change it to look like this: data = [{Key one: 'value1', Ke ...