Chrome的网络推送通知[关闭]

Posted

技术标签:

【中文标题】Chrome的网络推送通知[关闭]【英文标题】:Web Push Notification for Chrome [closed] 【发布时间】:2016-07-21 11:49:00 【问题描述】:

如何创建 Web Chrome 通知? 我一直在寻找如何使用有效负载创建 Web 推送 chrome 通知,经过不错的研发,我想与大家分享我的代码。

【问题讨论】:

【参考方案1】:
                         Client Side Code: 
    main.js

    function base64UrlToUint8Array(base64UrlData) 
      const padding = '='.repeat((4 - base64UrlData.length % 4) % 4);
      const base64 = (base64UrlData + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');
      const rawData = atob(base64);
      const buffer = new Uint8Array(rawData.length);
      for (let i = 0; i < rawData.length; ++i) 
        buffer[i] = rawData.charCodeAt(i);
      
      return buffer;
    
    (function() 
      if (!('serviceWorker' in navigator)) 
        return;
      
      return navigator.serviceWorker.register('sw.js')
      .then(function(registration) 
        console.log('service worker registered');
        return navigator.serviceWorker.ready;
      )
      .then(function(reg) 
        var channel = new MessageChannel();
        channel.port1.onmessage = function(e) 
          window.document.title = e.data;
        
        reg.active.postMessage('setup', [channel.port2]);
        var subscribeOptions =  userVisibleOnly: true ;
        // Figure out the vapid key
        var searchParam = window.location.search;
        vapidRegex = searchParam.match(/vapid=(.[^&]*)/);
        if (vapidRegex) 
          // Convert the base 64 encoded string
          subscribeOptions.applicationServerKey = base64UrlToUint8Array(vapidRegex[1]);
        
        console.log(subscribeOptions);
        return reg.pushManager.subscribe(subscribeOptions);
      )
      .then(function(subscription) 
        console.log(JSON.stringify(subscription));
        window.subscribeSuccess = true;
        window.testSubscription = JSON.stringify(subscription);
      )
      .catch(function(err) 
        window.subscribeSuccess = false;
        window.subscribeError = err;
      );
    )();


    sw.js

    'use strict';

    let port;
    let pushMessage;

    console.log('Started', self);

    self.addEventListener('install', function (event) 
      self.skipWaiting();
      console.log('Installed', event);
    );

    self.addEventListener('activate', function (event) 
      console.log('Activated', event);
    );

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

      event.waitUntil(
        self.registration.showNotification('Web Push Notification ', 
          body: payload,
          icon: 'images/abc.png',
        ));
    );

    self.addEventListener('notificationclick', function(event) 
      console.log('Notification click: tag', event.notification.tag);

      event.notification.close();
      var url = 'http://www.google.com/';

      event.waitUntil(
        clients.matchAll(
          type: 'window'
        )
        .then(function(windowClients) 
          console.log('WindowClients', windowClients);
          for (var i = 0; i < windowClients.length; i++) 
            var client = windowClients[i];
            console.log('WindowClient', client);
            if (client.url === url && 'focus' in client) 
              return client.focus();
            
          
          if (clients.openWindow) 
            return clients.openWindow(url);
          
        )
      );
    );

    .................................................................................
                            SERVER SIDE CODE:
    routers/notifications.js

    var express = require('express');
    var router = express.Router();
    var webPush = require('web-push');
    var gcmUrl = "https://android.googleapis.com/gcm/send/";

    //this key is coming from gcm project
    var GCM_API_KEY = "AIzaSyAI2OM3My5E8uulEGtQn31zfydBlCjhezZZWlpE";

    router.get('/', function (req, res, next) 
    res.send('Hello');
    )
    webPush.setGCMAPIKey(GCM_API_KEY);
    router.post('/', function (req, res, next) 
      var payload = req.body;
      console.log(payload);

      gcmUrl =  "https://android.googleapis.com/gcm/send/"+req.body.registrationId;

      console.log('sending request to GCM');

      webPush.sendNotification(gcmUrl, 
        RegistrationID: req.body.registrationId,
        TTL: req.body.ttl,
        payload: req.body.payload,
        userPublicKey: req.body.key,
        userAuth: req.body.authSecret,
      )
          .then(function (gcmResponse) 
          console.log('gcm: ', gcmResponse);
          res.sendStatus(201);
        ).catch(function (gcmError) 
          console.error("error frm gcm");
          console.log(gcmError);
        );

    );


    module.exports = router;
.................................................................................
                                   Sending Request:
I used postman to send notification.


    "ttl" : "5",
     "payload" :"Your Request #123 is accepted" ,
     "key" : "BBqMWJxSWFFcnvpowevnskdhdX0im4nADVSj9F_53xhxahcz-dnnR8wZv44o=",
     "authSecret" : "elOOVcwciiaaavkYiDA==",
     "registrationId": "doPVnhn3Ymc:APA91bFx_2tyfKs2xbpaocnakdrzdjS0ED9okiNEz-jECb3lC43kTqfltBZ54prNgtH3P_mBaDs5JOEQihhZld-E-vggxaUVUhyphe-oSoCE"
  

【讨论】:

【参考方案2】:

查看本指南,一点都不难

https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

【讨论】:

【参考方案3】:

以下是 Google Chrome 示例指南:https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web

【讨论】:

以上是关于Chrome的网络推送通知[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

网络推送通知未在 Chrome 中显示

节点 - 浏览器关闭时推送通知

Chrome 推送通知

网络推送通知未显示

网络推送通知不显示电脑是不是关闭或睡眠

Chrome 中的 OS X Mavericks 推送通知