«

chrome离线通知

emer 发布于 2020-11-3 10:49   1990 次阅读     


首先创建renderKey.js


const webpush = require('web-push');
//VAPID keys should only be generated only once.
const vapidKeys = webpush.generateVAPIDKeys();
console.log(vapidKeys.publicKey, vapidKeys.privateKey);

获取key后新建html文件引入js,如下

index.js

navigator.serviceWorker.register("sw.js").then(function(reg){
    console.log("Yes, it did register service worker.");
    if (window.PushManager) {
        reg.pushManager.getSubscription().then(subscription => {
            // 如果用户没有订阅
            if (!subscription) {
              console.log('没有订阅');
                subscribeUser(reg);
            } else {
                console.log("You have subscribed our notification",subscription);
            }       
        });     
    }
}).catch(function(err) {
    console.log("No it didn't. This happened: ", err)
});

function subscribeUser(swReg) {
  //后端生成的public key
  var applicationServerPublicKey='BMTDJhVkVFXYurncsdgoKhAlTo8fleSp_guJNHR32wHJfpQA9mkm9vXVVcyrsHi9bZIIVz6g4H2gAjVfFp8aSII';
    const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
    swReg.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: applicationServerKey
    })
    .then(function(subscription) {
      console.log(JSON.stringify(subscription));
    })
    .catch(function(err) {
      console.log('订阅失败: ', err);
    });
  }

  function urlB64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
      .replace(/\-/g, '+')
      .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }
  
目录内创建sw.js serverWorker

self.addEventListener('push', function(event) {
    console.log('event',event)

    const title = event.data.text();
    const options = {
      body: event.data.text(),
     // icon: './images/logo/logo512.png',
    };

    event.waitUntil(self.registration.showNotification(title, options));
  });

// 添加notificationclick事件监听器,在点击notification时触发
self.addEventListener('notificationclick', function(event) {
    // 关闭当前的弹窗
    event.notification.close();
    // 在新窗口打开页面
    event.waitUntil(
      clients.openWindow('https://google.com')
    );
  });

// // 触发一条通知
// self.registration.showNotification('您有新消息', {
//   body: 'Hello Service Worker',
//   //icon: './images/logo/logo152.png',
// });
打开网站,允许订阅,订阅后复制console内的返回值,创建server.js(后台),替换指定值后进行推送
const webpush = require('web-push');
// const vapidKeys = webpush.generateVAPIDKeys();
const vapidKeys = {
    publicKey: 'BMTDJhVkVFXYurncsdgoKhAlTo8fleSp_guJNHR32wHJfpQA9mkm9vXVVcyrsHi9bZIIVz6g4H2gAjVfFp8aSII',
    privateKey: 'L1OCeyVjzE2xr3hJ2ecZrBUnp7PsZQFt8njgff_dh4A'
  }
  webpush.setVapidDetails(
    'mailto:your@gmail.com',
    vapidKeys.publicKey,
    vapidKeys.privateKey
  )
  //fcm api key
  webpush.setGCMAPIKey('apikey');
  /**前端生成注册后返回的 */
const subscription = {"endpoint":"https://fcm.googleapis.com/fcm/send/dV-98OYa8XU:APA91bFGsvfVTQLxWlPYAz3uaWpRXiX8hSJZ-PDFoQUu9xzpBHnTjl4rU9QtlHoE0DyvT6u26RMdeMInaepjXyQMHZMxLdmZ_bu9ga5fsw9r3tt4oN-ANL_WEyAquYFv2fCBX8w-vtjL","expirationTime":null,"keys":{"p256dh":"BNXlNFqW-k8-xnf4rUu0T2FZ3goCBu8af8H6u_0jrkE_ByqBu_wZyq6QfDgcQTdOoBVxLrVOQ3iSorWmXaU_Z3Q","auth":"zbEcG5EwXNa5ni00Etoqew"}}
webpush.sendNotification(subscription, 'hello myname is push');
关闭网站,我们发现浏览器也能收到通知了




demo:https://github.com/lininn/webOfflinePush