redirect user after click on notification with js

Viewed 144

i'm using this code to push notification to my user:

Notification.requestPermission(function(result) {
                    if (result === 'granted') {
                        navigator.serviceWorker.ready
                            .then(function(registration) {
                                registration
                                    .showNotification('new message from ' + message.user, {
                                        body: message.message,
                                        vibrate: [200, 100, 200, 100, 200, 100, 200],
                                        tag: 'message'
                                    });
                            })
                        ;
                    }else {
                        alert('new message from ' + message.user + '\n please allow notification to get notification when a message receive.')
                    }
                });

how to redirect user to specific url after click on notification?

1 Answers

i try this and work, hope useful for others.

Notification.requestPermission(function(result) {
                    if (result === 'granted') {
                        navigator.serviceWorker.register('/sw.js');
                        navigator.serviceWorker.ready
                            .then(function(registration) {
                                registration
                                    .showNotification('new message from ' + message.user, {
                                        body: message.message,
                                        vibrate: [200, 100, 200, 100, 200, 100, 200],
                                        tag: 'message',
                                        data : {email: message.email}
                                    })
                                ;
                            })
                        ;
                    }else {
                        alert('new message from ' + message.user + '\n please allow notification to get notification when a message receive.')
                    }
                });

and in 'sw.js' file add this :

self.addEventListener('notificationclick', function(event) {
    clients.openWindow('url');
    event.notification.close();
}, false);
Related