Chrome Service Worker 推送通知仅在我网站的选项卡 URL 关闭或不活动时显示

Gad*_*med 5 service google-chrome worker push-notification google-cloud-messaging

我想仅当我的网站中没有打开的 chrome 选项卡或选项卡已打开且未选择(活动)时才显示 GCM 服务工作线程消息。

\n\n

这是我的代码。

\n\n

错误: chrome 未定义(\xe2\x80\xa6)。

\n\n

清单.json

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

service-worker.js

\n\n
    // The service worker running in background to receive the incoming\n// push notifications and user clicks\nself.addEventListener(\'push\', function(event) {  \n  // Since there is no payload data with the first version  \n  // of push messages, we\'ll grab some data from  \n  // an API and use it to populate a notification\n  var s_id=0;  \n  self.registration.pushManager.getSubscription().then(function(subscription) {\n\n   if(subscription!=null){\n\n   s_id= subscription.endpoint.split("/").slice(-1);\n\n   var mURL="https://www.webplusexpress.com";\n   var ok=true;\n\n\n   chrome.tabs.getAllInWindow(undefined, function(tabs) {\n    for (var i = 0;i<tabs.length; i++) {\n      if (tabs[i].url && (tabs[i].url.indexOf(mURL)!=-1)) {\n        //chrome.tabs.update(tab.id, {selected: true});\n        if(tabs[i].highlighted){\n          ok=false; \n        }  \n        return;\n      }\n    }\n\n  });\n\n   if (ok){\n   event.waitUntil(fetch(\'https://www.wpe.com/pushnotifyapi?s_id=\'+s_id).then(function(response) {  \n\n      if (response.status !== 200) {  \n        // Either show a message to the user explaining the error  \n        // or enter a generic message and handle the\n        // onnotificationclick event to direct the user to a web page  \n        console.log(\'Looks like there was a problem. Status Code: \' + response.status);  \n        throw new Error();  \n      }\n\n      // Examine the text in the response  \n      return response.json().then(function(data) {  \n        if (data.error || !data.notification) {  \n          console.error(\'The API returned an error.\', data.error);  \n          throw new Error();  \n        }  \n\n        var title = data.notification.title;  \n        var message = data.notification.message;  \n        var icon = data.notification.icon;  \n        console.log(\'icon received\'+icon);\n        var notificationTag = data.notification.tag;         \n\n        return self.registration.showNotification(title, {  \n          body: message,  \n          icon: icon,  \n          tag: notificationTag  \n        });  \n      });  \n    }).catch(function(err) {\n\n\n      console.error(\'Unable to retrieve data\', err);\n\n      var title = \'An error occurred\';\n      var message = \'We were unable to get the information for this push message\';  \n      var icon = \'https://www.webplusexpress.com/images/3web+carre.png\';  \n      var notificationTag = \'notification-error\';  \n      return self.registration.showNotification(title, {  \n          body: message,  \n          icon: icon,  \n          tag: notificationTag  \n        });  \n    }) \n\n  ); \n  }\n\n  }\n});\n\n});\n\n\nself.addEventListener(\'notificationclick\', function(event) {  \n  console.log(\'On notification click: \', event.notification.tag);  \n  // Android doesn\'t close the notification when you click on it  \n  // See: http://crbug.com/463146  \n  event.notification.close();\n\n  // This looks to see if the current is already open and  \n  // focuses if it is  \n  event.waitUntil(\n    clients.matchAll({  \n      type: "window"  \n    })\n    .then(function(clientList) {  \n      for (var i = 0; i < clientList.length; i++) {  \n        var client = clientList[i];  \n        if (client.url == \'/\' && \'focus\' in client)  \n          return client.focus();  \n      }  \n      if (clients.openWindow) {\n        return clients.openWindow(\'/\');  \n      }\n    })\n  );\n});\n
Run Code Online (Sandbox Code Playgroud)\n

Tey*_*yam 0

参考为Chrome 实现推送消息可能会有所帮助。它显示了为了支持 Web 应用程序中的推送消息而需要完成的每个步骤,其中在注册文件之前检查是否支持 Service Worker service-worker.js

除此之外,使用页面可见性 API来检测网页何时可见或处于焦点也可能有所帮助。当用户最小化网页或移动到另一个选项卡时,API 会发送一个visibilitychange有关页面可见性的事件,如 SO post 中所做的那样 -有没有办法检测浏览器窗口当前是否处于活动状态?