Notification Click Event for PWA Service Worker

I am attempting to display a notification and trigger an action when it is clicked.

    try {
    navigator.serviceWorker.getRegistration()
        .then(reg => {
            reg.showNotification("Check out the video clip!", {
                body: "Click here!",
                icon: "images/she_is_fire.png",
                vibrate: [100, 50, 100],
                tag: 'sample',
                actions: [{ action: 'explore', title: 'Watch', icon: 'images/she_is_fire.png' }],
            });
            self.addEventListener('notificationclick', function(event) {
                event.notification.close();
                window.open("https://youtu.be/PAvHeRGZ_lA");
            }, false);
        })
        .catch(err => alert('Service Worker registration error: ' + err));

} catch (err) {
    alert('Notification API error: ' + err);
}

I have added the event listener, but it does not seem to be triggering. What could I be doing wrong?

Answer №1

When it comes to handling clicks on Service Worker-based notifications, the correct place to do so is within the Service Worker itself. Make sure to transfer your listener - the section containing

self.addEventListener('notificationclick', ...)
- into your Service Worker code.

It's important to remember that you won't have access to window in this context. If you want to direct users to a URL upon clicking the notification, utilize clients.openWindow instead.

Therefore, your application-side code should only include the reg.showNotification call, while your handler in the Service Worker should be structured like this:

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  clients.openWindow("https://youtu.be/PAvHeRGZ_lA");
});

Answer №2

Don't forget, when you make changes to the code in your service-worker.js file (see answer), be sure to restart your browser so that the changes take effect. I learned this the hard way after spending too much time wondering why my changes weren't working!

Answer №3

To provide further clarification, here is the reason why the self keyword is used within a service worker file as explained in Google Web Fundamentals:

One of the trickiest parts of this code for many developers who are new to service workers is the self variable. In Web Workers, which include service workers, self is commonly used. It refers to the global scope, similar to how window is used in a web page. However, in the context of web workers and service workers, self actually refers to the worker itself.

reference

I decided to share this explanation because it helped me understand all these events better, especially the click event.

Answer №4

If you're attempting to check this out locally by using a browser window generated by visual studio, consider trying it in an alternative browser or deploying it for better results.

There seems to be a strange issue with VS and localhost that prevents this event from occurring.

I dedicated 2 hours to troubleshooting this problem. I hope sharing this information will help save time for others.

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 can I show tab objects in a Chrome extension?

I'm currently working on developing a new Google Chrome extension that focuses on tab organization. Despite the abundance of similar extensions already available, I am determined to create my own unique solution. One idea I have is to create a popup w ...

Is my front-end JavaScript fetch request mistakenly being sent as a GET instead of a POST?

On clicking the submit button, a fetch request is triggered. Strangely, in the developer tools, it shows up as a GET request. I tested the request using Insomnia and it returned the handlebars site to me without any of my console logs appearing on either ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data ...

What is the best way to extract value from an input text that is being repeated using ng-repeat within a Tr

Having a table with repeated rows in angular, you can also dynamically add new rows by clicking a button. If there are already 3 repeated rows and 2 extra rows are added with data entered, how can we retrieve all the data from the table in the controller ...

One project contains a pair of React instances

I am currently working on a React Web App and recently encountered an issue with an 'invalid hook call' error. Upon further investigation, I discovered that there are duplicate copies of the React library in my project, including within the CSS f ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

What is the best way to trigger the onclick event before onblur event?

I have two elements - an anchor with an onclick function and an input with an onfocus event. The anchor is toggled by the input button; meaning, when the button is in focus, the anchor is displayed, and when it loses focus, the anchor is hidden. I'm l ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...

Guide to establishing a connection with a Node.js socket server

I'm delving into the world of node JS and experimenting with creating a real-time application that involves a node JS server using socket.io, along with a unity application that can communicate with it. Below is the code I used to set up the server w ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

Regular expression to detect a space that is escaped

Given a string: rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3 Attempting to find a regex pattern that matches spaces, but ex ...

Place a new button at the bottom of the react-bootstrap-typeahead dropdown menu for additional functionality

Currently, I have successfully implemented the React Bootstrap Typeahead with the desired options which is a good start. Now, my next challenge is to integrate a custom button at the end of the dropdown list for performing a specific action that is not ne ...

Unforeseen anomalies arise when deleting an element from an array in a React application

I've been scouring for a solution, but I could really use some human guidance. I have a basic form where users can input additional fields. They also have the option to delete irrelevant fields. The problem arises when trying to remove these fields. ...

Jest snapshot tests using react-test-renderer encounter null references in refs

Having an issue with manually initializing the Quill editor in componentDidMount and encountering Jest test failures. It seems that the ref value I am receiving is null in jsdom. There is a related issue here: https://github.com/facebook/react/issues/7371, ...

Button halts the playback of numerous audio tracks simultaneously

I'm in the process of creating a Launchpad, where each row consists of 8 buttons/audio tracks and a stop button. My goal is for each stop button to halt all audio playing on that specific row when pressed—for instance, pressing Stop Button 1 would c ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...

What methods should I use to host my web application using Node/Express?

I have a question that may seem basic to some, but I'm completely lost when it comes to Node/Express. I have only worked with Apache servers (usually WAMP/XAMP for testing), so I have no clue how to serve my web app. My folder structure looks like th ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...