Error: An error occurred while trying to run the 'update' function on the ServiceWorkerRegistration object - Invalid invocation

Recently, I encountered a challenge with my VueJS app that was created using the CLI as a PWA. The issue stemmed from the service worker file, which is outlined below:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log(
        'App is being served from cache by a service worker.\n' +
          'For more details, visit https://<google-link>'
      )
    },
    registered(registration) {
      console.log('Service worker has been registered.')
      setInterval(registration.update, 1000 * 60 * 60)
    },
    cached() {
      console.log('Content has been cached for offline use.')
    },
    updatefound() {
      console.log('New content is downloading.')
    },
    updated(registration) {
      console.log('New content is available; please refresh.')
      document.dispatchEvent(new CustomEvent('swUpdated', { detail: registration }))
    },
    offline() {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error(error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

The problem arose when I received a

TypeError: Failed to execute 'update' on 'ServiceWorkerRegistration': Illegal invocation
error within the setInterval function while attempting to call registration.update. This interval checks for updates to the app every hour. Despite searching extensively, I could not pinpoint the cause of this issue. Hopefully, sharing this experience will assist others facing a similar predicament.

Answer №1

To resolve the issue, I successfully resolved it by enclosing registration.update within a function:

 registered(registration) {
      console.log('The Service worker has now been registered.')
      setInterval(() => {
        console.log('Initiating check for service worker update.')
        registration.update()
      }, 1000 * 60 * 60)
    },

A big thank you to this informative page that assisted me in solving this problem:

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

jQuery click() function fires twice when dealing with dynamic elements

I am loading content from a database through ajax into a div and then when clicking on any of these content pieces, it should reload new content. The ajax request is initialized as a method within a class that I call at the beginning: function Request(ta ...

Behind the scenes, unable to launch due to Schema Error

My experience with Backstage was going smoothly until I ran into an issue after executing a yarn install this afternoon. Now, whenever I attempt to run yarn dev, it fails with the following error: [0] Loaded config from app-config.yaml [0] <i> [webpa ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Display an image in response to a button click using JavaScript

I am currently working on a feature that will display information when a radio button is pressed. I also want to include an image, but I am facing an issue where the text displays correctly but the image does not appear. What steps should I take to resolve ...

I'm having trouble getting the drag event to work for Three.js trackball controls within a UIkit

The issue at hand involves a fullscreen Three.js canvas that is functioning perfectly, but there are limitations when displaying a preview in a UIkit modal – zooming works, but panning does not. JS: Renderer and Controls renderer = new THREE.WebGLRende ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Is there a way to stop Babel from transpiling JavaScript and wrapping its output in a define([], function(){}) block?

I am currently working on transpiling ES6 files to ES5 using Babel in order to be compatible with RequireJS (Magento 2). However, I have encountered an issue that has me stuck. Here is the Babel configuration: const presets = [ [ "@babel/ ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

Encountered an unexpected error while working on a Vue project, specifically related

When I created a Vue project on my local computer and then tried to transfer it to my work computers (which are on a closed server), the project did not run properly in both compiled (after running npm run build) and uncompiled versions. The error I encoun ...

The functionality of Object.assign in REACT is producing unexpected and incorrect results

Hey everyone, I have a project in React with 3 components. My goal is to extract the state from these 3 components and combine them into one JSON object on a final page. The components are not nested as child and parent, so my workaround was to set the st ...

What is the process for generating a new object by outputting key-value pairs?

I have an array that I'm trying to use to create a new object with specific keys and values. const arr = [ { name: 'ab', key: '584577', }, { name: 'cd', key: '344926', }, { name: &a ...

Steps for extracting all query parameters from a URL containing a redirect URL as one of the parameters

Below is the code snippet I am currently using to extract query parameters from the application URL. However, this logic fails when a URL is passed as a query param which includes its own query parameters. For example: Example: In this scenario, url2para ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Creating a dynamic object for a React component by utilizing props

I currently have a component that displays a grid of 6 items. These items are hard-coded as gridItems. My goal is to make this component dynamic by allowing it to render specific items based on props passed to it. Instead of always displaying 6 items, I ...

Using jasmine-node to create a spy on a constructor invoked within another function

As a beginner in Jasmine, I am looking to write unit tests for a node.js application using this framework. However, I am facing some challenges, one of which is described below: var sampleFunction = function(){ var loader = new Loader(params); // ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Latest versions of Bootstrap are facing issues with the functionality of the Carousel feature

I'm struggling to create a basic carousel, but for some reason, it's not functioning properly. I attempted to use the sample code provided by Bootstrap's documentation, but it doesn't behave as expected (slides won't transition and ...

The click event in an Angular 6 loop is not being activated

When the Test is clicked, the function should be invoked. However, nothing happens when I click on it. Here is the HTML component code: <div class="row m-0 justify-content-between" *ngFor="let i of k[currentk]?.details | keys"> <div (click ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...