首页 > 解决方案 > 使用服务工作者在 vue-cli 中为“推送”添加事件监听器

问题描述

我使用的是NodeJs 后端服务器,而对于我的前端 Web 应用程序,我使用的是 Vue-CLI。在开发模式下,后端位于一个端口上,localhost而前端应用程序位于另一个端口上。

我正在尝试通过使用 web-push npm 和 Vue CLI 附带的服务工作者来实现推送通知。但是,我不知道应该把eventListenerfor放在哪里'push'

service-worker.js我尝试在(前端/)主目录(在哪里)中创建一个名为的文件registerServiceWorker.js。在下面的代码中,我只是把文件扔进了eventListener文件中registerServiceWorker.js

提前致谢!

前端(registerServiceWorker.js):

/* eslint-disable no-console */
console.log('baseURL:', process.env.BASE_URL)
const BACKEND_SUBSCRIBE = (process.env.NODE_ENV !== 'development')
    ? '/subscribe'
    : '//localhost:3003/subscribe';

import { register } from 'register-service-worker'
import {convertedVapidKey} from './services/PushNotificationService'
import Axios from 'axios';
const axios = Axios.create({
  withCredentials: true
});

self.addEventListener('push', function(e) {
  console.log('Hi');
  const data = e.data.json();
  self.registration.showNotification(data.title, {
    body: 'Notified by me',
    icon: 'icon'
  });
});

if (process.env.NODE_ENV === 'development') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready (sw) {
      sw.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: convertedVapidKey
      }).then(sub => {
        console.log('sending sub', sub)
        axios.post(BACKEND_SUBSCRIBE, sub)
        .then(res => {
           console.log('sent sub,', res)
        });
      })
    },

后端(server.js):

const webpush = require('web-push');

const publicKey= 'keystring';
const privateKey = 'keystring'
webpush.setVapidDetails(
    'mailto:my@app.com',
    publicKey,
    privateKey
)

app.post('/subscribe', (req, res) => {
        const subscription = req.body;
        console.log(subscription);
        // send 201 status
        res.status(201).json({'see':'see this?'});

        // create payload
        const payload = JSON.stringify({ title: 'Push test'});

        webpush.sendNotification(subscription, payload)
        .catch(err => console.log(err));

})

标签: vue.jsservicecommand-line-interfaceprogressive-web-appsworker

解决方案


毕竟,我必须做的是在主前端配置一个“vue.config.js”文件,如下所示:

// vue.config.js
module.exports = {
    pwa: {
      workboxPluginMode: 'InjectManifest',
      workboxOptions: {
          swSrc: 'src/service-worker.js'
      },
      themeColor: '#8bc34a'
    },
  }

这使我可以将推送事件侦听器粘贴到 src/service-worker.js 文件中:)


推荐阅读