【问题标题】:How to set display duration for Push Notification in javascript?如何在 javascript 中设置推送通知的显示持续时间?
【发布时间】:2017-02-02 04:52:16
【问题描述】:

这里是监听推送通知的 service worker 的代码:

self.addEventListener('push', function (event) {
var payload = event.data ? event.data.text() : 'no payload';

event.waitUntil(
        self.registration.showNotification('Notify Message', {
            body: payload,
            icon: 'push.png'
        })   );

});

发送通知时,我的屏幕上会出现推送通知。但我想在屏幕上显示推送通知一段时间(例如 90 秒或发送通知的用户将输入的某个动态持续时间)。这不适用于 android 或 ios。这是桌面级通知。那么,如何设置推送通知的时长?

我们非常感谢任何形式的帮助。 谢谢

【问题讨论】:

  • 找到解决方案了吗?
  • 不,没有找到。

标签: javascript push-notification notifications service-worker


【解决方案1】:

您可以将 requireInteraction 参数设置为 true 以使通知不会自动关闭。 目前没有持续时间的参数。 你可以在这里查看文档 https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification

【讨论】:

    【解决方案2】:

    在不了解您如何显示通知的情况下,您能否实现一个简单的超时,类似于:

    function clearNotice(notice) {
        // notice.hide();
    }
    
    function showNotice(notice) {
        notice.show();
        // clear your notice
        setTimeout(clearNotice(notice), notice.timeout);
    }
    

    【讨论】:

      【解决方案3】:

      没有可用的侦听器或属性来设置持续时间。您可以使用以下代码关闭通知

      Notification.requestPermission(function(result) {
      if (result === 'granted') {
        navigator.serviceWorker.ready.then(function(registration) {
          registration.showNotification('Notify Message', {
            body: payload,
            icon: 'push.png'
          }).then(function(event) {
               console.log(event);
                if(event && event.notification) {
                  setTimeout(function(){ event.notification.close();}, 3000);
             }
        });
        });
      }
      

      });

      【讨论】:

      • 我收到 TypeError: event is undefined in promise。但我收到了通知。
      • 在上面的代码中给出 self.registration 并检查是否(event.Notifcation)然后关闭。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多