如何指定Chrome推送通知的时间限制

时间:2016-02-25 10:39:41

标签: google-chrome push-notification web-push chrome-gcm

我使用Service Worker将推送通知发送到Chrome浏览器。

我使用以下代码接收来自服务器的通知

 var url = "path/to/your/json/file/json-data.php?param="+Math.random();
 self.addEventListener('push', function(event) {    
  event.waitUntil(  
    fetch(url).then(function(response) {  
      if (response.status !== 200) {  
        // Either show a message to the user explaining the error  
        // or enter a generic message and handle the
        // onnotificationclick event to direct the user to a web page  
        console.log('Looks like there was a problem. Status Code: ' + response.status);  
        throw new Error();  
      }

      // Examine the text in the response  
      return response.json().then(function(data) {  
        if (data.error || !data.notification) {  
          console.log('The API returned an error.', data.error);  
          throw new Error();  
        }  
        var title = data.notification.title;  
        var message = data.notification.message;  
        var icon = data.notification.icon;  

        return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          data: {
            url: data.notification.url
          }  
        });  
      });  
    }).catch(function(err) {  
      console.log('Unable to retrieve data', err);

      var title = 'An error occurred';
      var message = 'We were unable to get the information for this push message';  
      var icon = 'img/design19.jpg';  
      var notificationTag = 'notification-error';  
      return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
    })  
  );  
});

// The user has clicked on the notification ...
self.addEventListener('notificationclick', function(event) {  
  console.log(event.notification.data.url);
  // Android doesn't close the notification when you click on it  
  // See: http://crbug.com/463146  
  event.notification.close();

  // This looks to see if the current is already open and  
  // focuses if it is  
  event.waitUntil(
    clients.matchAll({  
      type: "window"  
    })
    .then(function(clientList) {  
      for (var i = 0; i < clientList.length; i++) {  
        var client = clientList[i];  
        if (client.url == '/' && 'focus' in client)  
          return client.focus();  
      }  
      if (clients.openWindow) {
        return clients.openWindow(event.notification.data.url);  
      }
    })
  );
});

通知正在显示,但几秒后它就会关闭。我不需要关闭通知。用户明确关闭通知。告诉我停止关闭通知的代码。显示通知后,它不会永远关闭。用户明确关闭通知

1 个答案:

答案 0 :(得分:2)

return self.registration.showNotification(title,{
          身体:消息,
          图标:图标,
          tag:notificationTag
        });

您可以将requireInteraction:true添加到通知porperties字典中。这将使它保持在屏幕上。请注意,这并不能保证在所有平台上都可以使用,但至少在Chrome桌面上它可以正常工作。