Chrome服务工作者推送通知仅在我的网站的标签网址已关闭或未激活时显示

时间:2016-04-26 22:47:58

标签: google-chrome service push-notification google-cloud-messaging worker

我希望仅在我的网站中没有打开的Chrome标签或标签打开且未选中(有效)时才显示GCM服务工作者消息。

这是我的代码。

错误:未定义chrome(...)。

的manifest.json

 {  
  "name": "Webplus Express",  
  "short_name": "Webplus Express",  
  "icons": [{  
    "src": "https://raw.githubusercontent.com/deanhume/typography/gh-pages/icons/typography.png",  
    "sizes": "192x192",
    "type": "image/png" 
    }],  
    "start_url": "/index.html",  
    "display": "standalone",  
    "gcm_sender_id": "298340340811",
    "gcm_user_visible_only": true,
    "background": {
    "scripts": ["service-worker.js"]
    },    
    "permissions": [
    "gcm","tabs","activeTab"
    ]  
  }

服务worker.js

    // The service worker running in background to receive the incoming
// push notifications and user clicks
self.addEventListener('push', function(event) {  
  // Since there is no payload data with the first version  
  // of push messages, we'll grab some data from  
  // an API and use it to populate a notification
  var s_id=0;  
  self.registration.pushManager.getSubscription().then(function(subscription) {

   if(subscription!=null){

   s_id= subscription.endpoint.split("/").slice(-1);

   var mURL="https://www.webplusexpress.com";
   var ok=true;


   chrome.tabs.getAllInWindow(undefined, function(tabs) {
    for (var i = 0;i<tabs.length; i++) {
      if (tabs[i].url && (tabs[i].url.indexOf(mURL)!=-1)) {
        //chrome.tabs.update(tab.id, {selected: true});
        if(tabs[i].highlighted){
          ok=false; 
        }  
        return;
      }
    }

  });

   if (ok){
   event.waitUntil(fetch('https://www.wpe.com/pushnotifyapi?s_id='+s_id).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.error('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;  
        console.log('icon received'+icon);
        var notificationTag = data.notification.tag;         

        return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
      });  
    }).catch(function(err) {


      console.error('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 = 'https://www.webplusexpress.com/images/3web+carre.png';  
      var notificationTag = 'notification-error';  
      return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
    }) 

  ); 
  }

  }
});

});


self.addEventListener('notificationclick', function(event) {  
  console.log('On notification click: ', event.notification.tag);  
  // 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('/');  
      }
    })
  );
});

1 个答案:

答案 0 :(得分:0)

参考Implementing Push Messaging for Chrome可能有所帮助。它显示了您需要完成的每个步骤,以便在您的Web应用程序中支持推送消息传递,其中在注册service-worker.js文件之前检查服务工作者是否受支持。

除此之外,使用Page Visibility API检测网页何时可见或焦点也可能有所帮助。当用户最小化网页或移动到另一个标签页时,API会发送关于页面可见性的visibilitychange事件,如SO帖子所述 - Is there a way to detect if a browser window is not currently active?