javascript - Chrome推送通知-点击后如何打开URL地址?

标签 javascript google-chrome push-notification

我是 Google Chrome 推送通知的新手,我刚刚在 stackoverflow 上阅读了一些问题和答案,我以这个简单的推送通知 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',
                });

            });
        }
    });

}

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

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

请帮忙。谢谢。

最佳答案

我猜您在 Service Worker 上下文中,因为这是接收推送通知的地方。所以你有 self 对象来添加一个事件监听器,它会对通知的点击使用react。

(将此代码放在您的 sw.js 文件中,这是您的 Service Worker 脚本。)

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);
            }
        })
    );
});

关于javascript - Chrome推送通知-点击后如何打开URL地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39418545/

相关文章:

google-chrome - 打包应用程序 - 从应用程序商店外部安装

javascript - 闭包变量对内存的影响

javascript - 单击时更改所有按钮的颜色

html - 无法在 x3dom 中使用 indexedfaceSet 为面部着色

android - 如何让我的 1024 宽网页显示在我的 Chrome 中的 Nexus 7 上?

android - 无需谷歌云消息(GCM)将通知从 PC 推送到 android

javascript - 显示 DIV 元素之一,具体取决于用户输入值

javascript - jQuery 缓和问题

android - Mobilefirst 7.1 中带有状态栏的推送通知

ionic-framework - OneSignal 如何将 Push 发送到特定设备 - ionic