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

36

我是新手,初次接触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”语法的示例。

请帮忙,谢谢。

4个回答

73

我猜测您正在Service Worker上下文中,因为那里是接收推送通知的地方。所以您有self对象来添加一个事件监听器,以便在通知被点击时做出反应。

(将这段代码放入您的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);
            }
        })
    );
});

4
为了让它正常工作,我需要进行修改,使用 clients.matchAll({ includeUncontrolled: true, type: 'window' })。 - patrick
2
这个神秘的未定义变量“clients”应该是什么? - stackers
2
@stackers https://developer.mozilla.org/zh-CN/docs/Web/API/Clients - C14L
我应该把这个事件监听器放在哪里?在我的 FCM 服务工作者中还是其他地方?因为我尝试在 FCM 服务工作者中使用它,但它对我没有起作用。 - S.Aminnejad
完美运行,@S.Aminnejad 您可以将其放置在 firebase-messaging-sw.js 中。 - Duc Trung Mai
2
直到我将 matchAll({type: 'window'}) 更改为 matchAll({includeUncontrolled: true}),它才开始对我起作用。此外,我搜索主机而不是精确的 URL。 - user3502626

27

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

下面是用于FCM推送通知的Service Worker示例:

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

使用以下代码处理点击事件:

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

希望能对你有所帮助!


10

(此代码指的是Firebase Messaging)我也在寻找解决方案,答案非常简单,但没有文档明确说明。您需要在通知json中放置“click_action”=“您的网址”。以下是一个示例:

notification: {
          title: "Come",
          icon: '../../../../assets/logo.png',
          vibrate: [300,100,400,100,400,100,400],
          body: "some text",
          click_action : "your link"
         }

希望这能有所帮助。

1
其他的答案都没有用......点击通知什么也没打开。这个答案可行且简单得多。 - Skeets
5
"click_action" 不是官方浏览器通知 API 的一部分。上面的回答仅适用于 Firebase 推送通知。 - wirher
官方通知 API 中没有这样的选项: https://developer.mozilla.org/zh-CN/docs/Web/API/Notification - IStranger

0
{

 "notification": {

   "title": "Hey there",

   "body": "Subscribe to might ghost hack youtube channel",

   "click_action" : "http://localhost:4200"

 },

 "to":"YOUR_TOKEN"

}

这对我有用

"@angular/fire": "^6.1.5",

"firebase": "^7.0 || ^8.0"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接