当前位置: 首页 > 知识库问答 >
问题:

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

封俊艾
2023-03-14

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

请帮帮忙。多谢了。

共有1个答案

郭思淼
2023-03-14

我猜您是在服务工作者上下文中,因为那是接收推送通知的地方。因此,您有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);
            }
        })
    );
});
 类似资料:
  • > firebaseService类 公共类FirebaseMessagingService扩展了com.google.firebase.messaging。FirebaseMessagingService{private static int count=0;@Override public void onMessageReceived(@NonNull RemoteMessage Remote

  • 我使用firebase_消息和Flatter_local_通知包,目前我可以在应用程序处于后台时,在用户点击通知时获取通知数据。当应用程序位于前台时,我如何收听点击事件。

  • 当应用程序关闭时,我在使用FCM的聊天中收到有关新消息的通知。当我点击它时,我想打开聊天活动,但主活动会打开。 点击推送通知将打开主活动。在其中,我可以从intent获得一种类型的通知,并打开另一个活动: 在我看来,这种方法既肮脏又不方便。是否可以指定单击推送通知时将打开的活动? 编辑:解决问题的步骤: > 为要打开的活动添加意图过滤器: 向FCM消息添加click_action="you-act

  • 我有,可以向我的用户发送消息。 然而,我想做一个场景,如果我的用户点击他们的手机上的通知消息,然后应用程序将打开一个视图或弹出,并做一些后台任务。 这可能吗? 谢谢你 ===更新Shady Boshra建议的问题 1)我使用创建google cloud Function的firebase: 2)我更新我的移动应用程序代码/: 然后我尝试发送推送通知时,应用程序是打开模式。 然而,当我试图调试它时,

  • 我已经检查了react native onesignal github README,似乎获得通知的唯一方法是通过onNotificationOpen()回调打开。 他们的文件表明: 当打开或接收到任何通知时,调用回调传递带有通知数据的对象。 但是,显然不起作用。 有没有办法在不打开推送通知或启用应用内警报通知的情况下获取通知?