Alert from Google Chrome about Service Worker

My situation involves using FCM for sending web notifications. However, I am encountering a warning and the notifications are not functioning as expected when clicked (i.e., opening the notification URL). Below is my Service-Worker code:

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '<my senderid>'
});

const messaging = firebase.messaging();


messaging.setBackgroundMessageHandler(function(payload) {


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

    var promise = new Promise(function(resolve) {
      setTimeout(resolve, 1000);
    }).then(function() {
      return clients.openWindow(payload.data.locator);
    });

    event.waitUntil(promise);
  });

  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon
  };
  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

firebase-messaging-sw.js:108 Event handler of 'notificationclick' event must be added on the initial evaluation of worker script.

This is the warning message, with line 108 referring to this specific line:

self.addEventListener('notificationclick', function(event) {

It's worth noting that this issue occurs in Chrome version 55. Interestingly, Firefox does not encounter any problems and everything works fine. Thank you in advance.

Answer №1

It is recommended to relocate

self.addEventListener 

to a position outside the function block

messaging.setBackgroundMessageHandler

This ensures that the EventListener is added just once.

The complete code must appear as follows:

const messaging = firebase.messaging();

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

    var promise = new Promise(function(resolve) {
      setTimeout(resolve, 1000);
    }).then(function() {
      return clients.openWindow(event.data.locator);
    });

    event.waitUntil(promise);
  });

messaging.setBackgroundMessageHandler(function(payload) {   

  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    locator:payload.data.locator
  };
  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

Answer №2

Remember to utilize self.addEventListener outside of the messaging.setBackgroundMessageHandler function and access the data property within the notificationOptions

Below is the entire content of the firebase-messaging-sw.js file for improved comprehension

importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-messaging.js');

// Initialize Firebase
var config = {
  apiKey: "yourapikey",
  authDomain: "yourauthdomain",
  databaseURL: "yourdatabaseurl",
  projectId: "yourprojectid",
  storageBucket: "yourstoragebucket",
  messagingSenderId: "111111111111"
};
firebase.initializeApp(config);

var messaging = firebase.messaging();

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

    var promise = new Promise(function(resolve) {
      setTimeout(resolve, 500);
    }).then(function() {
      return clients.openWindow(event.notification.data);
    });
    event.waitUntil(promise);
});


messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    vibrate: [200, 100, 200, 100, 200, 100, 200],
    image: payload.data.image,
    data: payload.data.link,
    tag: "bg"
  };

  return self.registration.showNotification(notificationTitle, notificationOptions);
});

Answer №3

options.add_argument('--log-level=3')

It's just that easy

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

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Step-by-step guide to accessing the detail view upon selecting a table row in react.js

In my project, I have a table with multiple rows. When a row is selected, I want to display detailed information about that particular item. To achieve this functionality, I am utilizing react-router-dom v6 and MUI's material table component. Here is ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

Does anyone know of a tool that allows you to save HTML as a standalone page?

Looking for a solution to easily send standalone .html files with no external dependencies to clients on a regular basis. The original pages are built using node.js and express, and feature libraries like High Charts. Up until now, I have been manually pre ...

Is there a way to serve server-side rendered content exclusively to search engine crawlers like Google Bot, without SSR for regular users in Next.js?

With a staggering number of users visiting the site every day, we are making strides to enhance our visibility on Google by implementing SSR (which may sound unbelievable) and achieving a richer preview when content is shared on messaging platforms. As th ...

What techniques can be used to optimize Angular template integration and minimize http requests?

Situation: Our team is currently in the process of migrating an ASP.NET application from traditional WebForms to Web API + Angular. The application is primarily used in regions with limited internet connectivity, where latency issues overshadow bandwidth c ...

Using numerical symbols in multiple tooltips to convert dates into timestamps in the R programming language

When using the highcharter package in R, I am attempting to plot multiple line charts simultaneously. The challenge arises when dealing with different datasets containing values ranging from millions to billions, requiring a numeric symbols formatter imple ...

What is the best way to format a date as "2020-01-16 07:29:43.657519000 Z" using JavaScript?

Upon discovering a format 2020-01-16 07:29:43.657519000 Z in a project, I am curious about the significance of the numbers 657519000 and how to replicate this precise format using JavaScript. When attempting new Date().toISOString(), I receive 2020-05-27T2 ...

JavaScript Alert: The Ajax XMLHttpRequest Response has Returned Null

Below is the code snippet: <script type="text/javascript"> var xmlhttp; $(document).ready(function (){ xmlhttp=new XMLHttpRequest(); ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

Are the features of emulation mode in IE11 identical to implementing the meta EmulateIE7 tag?

When using the IE11 browser, I encountered an interesting message on the console: “HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.” Upon researching this error code on this link, I found out that it is a mode configured by IT ...

Can all actions in the ofType operator be waited for before calling next?

I have a list of dynamic redux actions that I need to monitor in order to trigger another action in my epic once all of them have been called. The key here is that the actions within this list can change and are not fixed. It would be ideal if the ofType o ...

Using ReactJS to create a Stacked Bar chart

I am encountering some challenges while trying to create a single stacked bar graph using data from an API. 1- The data I receive is not rounded, even when using % values. 2- Additionally, the total percentage does not always add up to 100%, causing the ...

Obtaining the clicked element within a functional component in React

I'm having trouble in React because I am unable to select the clicked element. The use of "this" in a functional component is not functioning as expected. function Test(data) { function getElement() { } return ( <div> ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG <svg width="200" height="200"> <g id="group"> <rect x="10" y="10" width="50" height="20" fill="teal"></rect> <circle cx=" ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

The exceptional speed of jQuery's each method sets it apart

I'm currently facing an issue where I am unable to successfully add the attribute data-size to my parent div. My code snippet is as follows: var width, height; $(".galerie img").each(function() { width = this.naturalWidth; height = this.naturalH ...