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

问题描述 投票:6回答:3

我是谷歌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”语法的示例。

请帮忙。谢谢。

javascript google-chrome push-notification
3个回答
20
投票

我猜你在服务工作者的上下文中,因为那是收到推送通知的地方。因此,您可以使用self对象添加事件侦听器,这将对通知的单击作出反应。

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

1
投票

这里有两个网站可以帮到你。

您必须先通知可点击的通知,然后您可以附加您想要打开的网址

https://groups.google.com/a/chromium.org/forum/m/#!topic/chromium-extensions/nevc6nRpAlQ

https://developer.chrome.com/extensions/notifications#event-onClicked

希望能帮助到你 :)


1
投票

如果您想打开带有从FCM推送通知或任何其他网络推送通知收到的动态URL的网站

以下是用于FCM推送通知的服务工作者的示例

messaging.setBackgroundMessageHandler(function(payload) {

    console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    data: { url:payload.data.click_action }, //the url which we gonna use later
    actions: [{action: "open_url", title: "Read Now"}]
  };

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

并使用以下代码处理click事件

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

  switch(event.action){
    case 'open_url':
    clients.openWindow(event.notification.data.url); //which we got from above
    break;
    case 'any_other_action':
    clients.openWindow("https://www.example.com");
    break;
  }
}
, false);

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.