我只有 HTML 和服务人员简单网站我做了
尝试在这里实现通知功能????
酱
https://github.com/GitHub30/web-push-study
第一的,地点打开以获得控制台。
铬( Ctrl + Shift + J )
火狐 ( Ctrl + Shift + K )
如果您看到 allow pasting,请在键盘上输入允许粘贴
在控制台中输入代码并回车运行它。
第 1 行 获取通知权限
await Notification.requestPermission()
点击左上角的許可する
第 2 行注册 service worker
navigator.serviceWorker.register('./service-worker.js')
第 3 行 准备密钥
var applicationServerKey = 'BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXKpNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo'
创建密钥时
var vapidDetails = await fetch('https://web-push-server.vercel.app/api/generateKeys').then(r=>r.json())
你也可以使用 Node.js、Python、OpenSSL 来实现。
https://github.com/web-push-libs/web-push#generatevapidkeys
https://gist.github.com/cjies/cc014d55976db80f610cd94ccb2ab21e
https://github.com/zivver/web-push/blob/master/README.md#using-openssl
第 4 行 获取订阅
var subscription = (await (await navigator.serviceWorker.ready).pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })).toJSON()
将公钥设置为applicationServerKey。
如果您创建了密钥
var subscription = (await (await navigator.serviceWorker.ready).pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidDetails.publicKey })).toJSON()
第 5 行发送推送通知
fetch('https://web-push-server.vercel.app/api/send', {
method: 'POST',
body: JSON.stringify({ subscription, payload: { title: 'やあ????' } })
})
如果您创建了密钥
fetch('https://web-push-server.vercel.app/api/send', {
method: 'POST',
body: JSON.stringify({ vapidDetails, subscription, payload: { title: 'やあ????' } })
})
我会将生成的密钥发送给您。
您还可以使用 Node.js 或 Python 轻松发送。
https://github.com/web-push-libs/web-push
https://github.com/web-push-libs/pywebpush
用卷曲发送
copy(`curl https://web-push-server.vercel.app/api/send -d '${JSON.stringify({ subscription, payload: { title: 'やあ????' } })}'`)
如果您创建了密钥
copy(`curl https://web-push-server.vercel.app/api/send -d '${JSON.stringify({ vapidDetails, subscription, payload: { title: 'やあ????' } })}'`)
我会将生成的密钥发送给您。
您还可以在Network 选项卡上复制send。 Windows 用户可以使用 PowerShell。
也可以转换为 Python 和 PHP。
点击设置链接
fetch('https://web-push-server.vercel.app/api/send', {
method: 'POST',
body: JSON.stringify({
subscription,
payload: { title: 'Open Yahoo!', data: { url: 'https://www.yahoo.co.jp/' } }
})
})
创建一个动作按钮
您还可以创建操作。
fetch('https://web-push-server.vercel.app/api/send', {
method: 'POST',
body: JSON.stringify({
subscription,
payload: {
title: 'やあ????',
body: 'どこに行きますか?????',
actions: [
{ title: 'visit Google', action: 'https://google.co.jp/' },
{ title: 'visit Mozilla', action: 'https://www.mozilla.org/' }
]
}
})
})
您还可以更改图标、优先级、振动和声音。
后记
我对上面的步骤做了一个演示。如果您可以将其用作参考,我很高兴。
酱
https://github.com/GitHub30/web-push-demo
参考
https://web-push-server.vercel.app实施
https://github.com/GitHub30/web-push-server
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308622234.html