The JavaScript function prints the variable using `console.log(var)`, however, it does not assign `var2` to

I've been following a tutorial on implementing push notifications in VueJS from this link.

After running the register function on the created hook, I encountered an issue:

register() {
      if ("serviceWorker" in navigator && "PushManager" in window) {
        console.log("Service Worker and Push is supported");

        navigator.serviceWorker
          .register("/sw.js")
          .then(function (swReg) {
            console.log("Service Worker is registered", swReg);
            swRegistration = swReg;
          })
          .catch(function (error) {
            console.error("Service Worker Error", error);
          });
      } else {
        console.warn("Push messaging is not supported");
        pushButton.textContent = "Push Not Supported";
      }
    }

When checking the console in Chrome, Safari, and Firefox, I noticed the following outputs:

"Service Worker and Push is supported"
"Service Worker is registered >ServiceWorkerRegistration"
"Service Worker Error ReferenceError: swRegistration is not defined"

I'm puzzled as to why swReg can be logged, but swRegistration remains undefined. Any ideas or suggestions?

.then(function (swReg) {
                console.log("Service Worker is registered", swReg);
                swRegistration = swReg;

Answer №1

Make sure to establish the swRegistration variable first, as this will prevent encountering the same issue with the swReg which is a result of the register promise.

register() {
      let swRegistration = null;
      if ("serviceWorker" in navigator && "PushManager" in window) {
        console.log("Service Worker and Push is supported");

        navigator.serviceWorker
          .register("/sw.js")
          .then(function (swReg) {
            console.log("Service Worker is registered", swReg);
            swRegistration = swReg;
          })
          .catch(function (error) {
            console.error("Service Worker Error", error);
          });
      } else {
        console.warn("Push messaging is not supported");
        pushButton.textContent = "Push Not Supported";
      }
    }

Answer №2

Perhaps the reason could be that swRegistration is not defined yet. To fix this, you could try adding let swRegistration at the beginning of your code snippet. Doing so should resolve the issue for you. Have a great coding experience!

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

Mapping prop passed to client component in NEXT 13: A step-by-step guide

Hello, I'm currently navigating through the Next 13 APP directory and have encountered a scenario where everything functions smoothly when I integrate the server component as shown below: const Tasks = async () => { const { tasks } = await getAll ...

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

Issue with React sending a Get request to a Node server using Express

Here is a snippet of code from my React app where I am trying to retrieve data from my database based on a value that is passed. Let's start by examining the section of code that may be causing an issue: Within one of my forms, there is a function th ...

Extract data from an array in MongoDB by organizing it into sections based on dates

As a beginner in the world of MongoDB, I'm trying to figure out how to extract data from an array in separate sections. { "name":"User name", "messages":[ { "message":"Message 1", ...

Is it possible to execute a function upon exiting my Node application?

Currently, I'm developing a project for my school using Node.js on a Raspberry Pi. The script I have created will be running for extended periods of time to control LEDs. Is there a method that allows me to execute a function upon exiting the program ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

The art of controlling iframe elements with jquery

I've been researching various topics related to this issue, but I'm still unable to achieve the desired outcome. Currently, I am embedding an iframe within an HTML document like so: <iframe class="full-screen-preview__frame" id="nitseditpre ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

A variable named "quid" has been set with a value of "x" in the session scope

I am trying to figure out how to set a parameter x in JSTL for a function I have, but when I input values as "x" it returns as a string. JS: function updateValue(x) { <q:set var="quid" value="x" scope="session"/> } HTML ...

Adjust the size of three panels (left, middle, right) using Javascript, ensuring that the middle panel remains unchanged in size

I am a newcomer to JavaScript and currently working with HTML, CSS, and JS files. I have three panels - left, center, and right - that I want to resize. The left panel resizes correctly when dragging the column border. https://i.stack.imgur.com/LxhUX.png ...

Issues with Javascript positioning in Chrome and Safari are causing some functionality to malfunction

My Javascript script is designed to keep an image centered in the window even when the window is smaller than the image. It achieves this by adjusting the left offset of the image so that its center aligns with the center of the screen. If the window is la ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

Automatically reload a particular webpage upon closing a pop-up window (using jQuery)

I am facing an issue with a pop-up named PopUp1 on page0.aspx. The problem occurs when a user clicks on a row in the GridView within PopUp1, causing another pop-up to launch, loading my page1.aspx. The complication arises when the user navigates through l ...

The HTML and JavaScript implementation of the Game of Life is experiencing technical difficulties

I attempted to create my own version of the Game of Life using HTML canvas and JavaScript. With the aid of various online tutorials, I was able to write a piece of code that I am still confident in. However, upon launching the HTML page in the browser and ...

Having trouble updating information using axios and vue-python

I encountered a problem while attempting to update an element from my form. Here is the code snippet: <script setup> const updateSupply = async () => { console.log("Test"); errors.value = "" try { ...

What are the best techniques for distinguishing the selected selector in jQuery?

$('#select_id1, #select_id2, #select_id3').change(function() { // Depending on which select element has changed, 'str' should be set accordingly. // For '#select_id1', 'str' should be equal to 'select_id ...

Issues arising from using Android Studio in conjunction with Quasar framework

I am currently working with quasar and I attempted to start the project using these commands: quasar build -m capacitor -T android quasar dev -m capacitor -T android Unfortunately, when I entered the first command, I encountered this error: FAILURE: Build ...

Leveraging JavaScript for setting an ASP.net Dropdownlist

I have made several attempts to set the dropdownlist without success. Despite observing the selectedIndex changing appropriately in developer tools, and noticing the selected option node change from false to true, the dropdownlist still displays the first ...

Exploring the process of defining directives with Vue 3's composition API

How can directives be defined and used in Vue3's composition API using the new syntactic sugar in SFC <script setup> format? In the past, with the options API, it looked something like this: import click_outside from "@/directives/click-out ...