vue.js - 使用服务工作者在 vue-cli 中为“推送”添加事件监听器
问题描述
我使用的是NodeJs 后端服务器,而对于我的前端 Web 应用程序,我使用的是 Vue-CLI。在开发模式下,后端位于一个端口上,localhost
而前端应用程序位于另一个端口上。
我正在尝试通过使用 web-push npm 和 Vue CLI 附带的服务工作者来实现推送通知。但是,我不知道应该把eventListener
for放在哪里'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.config.js”文件,如下所示:
// vue.config.js
module.exports = {
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'src/service-worker.js'
},
themeColor: '#8bc34a'
},
}
这使我可以将推送事件侦听器粘贴到 src/service-worker.js 文件中:)
推荐阅读
- angular - Angular 自定义元素和 Angular 8 材质:MatDialog 和 MatMenu 不起作用
- r - 是否可以从文件标题中获取信息?
- kubernetes - 存储假 SSL 证书的 Kubernetes nginx 入口意外错误:无法创建 PEM 证书文件
- javascript - Node.js 服务器调用 HTML 调用 Javascript 模块:不允许的 MIME 类型和/或未定义“要求”
- ffmpeg - 初始化后如何更改 AVCodecContext 的设置(FFMPEG)
- php - 查询日期并在 HTML 日期输入中显示
- ios - 何时从 UITableCellView 中删除自定义 Click-Event
- postgresql - 在 Postgresql 的 BEFORE INSERT 触发器中更改多列的值
- wordpress - 如何在 Wordpress 的“Events Schedule WP Plugin”中添加年度搜索
- php - 如何将旧 URL 从自定义 PHP 网站重定向到新的 WordPress URL?