Chrome推送通知 - 点击后如何打开网址? [英] Chrome push notification - how to open URL adress after click?

查看:291
本文介绍了Chrome推送通知 - 点击后如何打开网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Google Chrome推送通知的新手,我刚刚在这里阅读了一些问题和解答,在stackoverflow上,我已经以这个简单的推送通知javascript结束。

I am new to Google Chrome Push notifications and I was just reading some questions and answers here, on stackoverflow and I have ended with this easy push notification javascript.

  navigator.serviceWorker.register('sw.js');

function notify() {

    Notification.requestPermission(function(result) {

        if (result === 'granted') {
           navigator.serviceWorker.ready.then(function(registration) {

                registration.showNotification('test notification', {
                    body: 'Hey I am test!',
                    icon: 'image.png',
                });

            });
        }
    });

}

它只是简单的通知,但我需要打开一个新窗口与其他网页在点击通知后。

Its just simple notification, but I need open a new window with other webpage after click on notification.

我知道这是可能的,但我找不到使用serviceWorker语法的示例。

I know it is possible, but I cant find examples using "serviceWorker" syntax.

请帮忙。谢谢。

推荐答案

我猜你正在服务工作者上下文中,因为那是接收推送通知的地方。所以你有 self 对象添加一个事件监听器,这会对点击通知做出反应。

I am guessing you are in a Service Worker context, because that's where Push Notifications are received. So you have the self object to add a event listener to, that will react to a click on the notification.

self.addEventListener('notificationclick', function(event) {
    let url = 'https://example.com/some-path/';
    event.notification.close(); // Android needs explicit close.
    event.waitUntil(
        clients.matchAll({type: 'window'}).then( windowClients => {
            // Check if there is already a window/tab open with the target URL
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];
                // If so, just focus it.
                if (client.url === url && 'focus' in client) {
                    return client.focus();
                }
            }
            // If not, then open the target URL in a new window/tab.
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );
});

这篇关于Chrome推送通知 - 点击后如何打开网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆