webpush sdk
npm install @efox/webpushwebpushwebpushppppwebpush sdk
js
npm i @efox/webpush
or
yarn add @efox/webpush
`使用
` js
import WebPush from '@efox/webpush'
`实例化
` js
const wp = new WebPush({
applicationServerPublicKey: '',
swjsurl: /sw.js?v=${new Date() * 1}, // 格外的sw.js 需要项目方提供,这里是填 sw.js 路径 sw.js 内容见下文
appid: '', // 系统标识
uid: 50015308, // 业务用户uid
lang: 'zh', // 语言
online: 1, // 在线状态,0:离线,1:在线,@see Online
env: 'test' // test 测试环境 pro 生产环境 也可以为带 http的字符串,直接配host
})
`
初始化
`js
wp.init().then((resp)=> {
console.log('after init', resp)
wp.subscribeUser(wp.getPushKey()) // 订阅
})
`API
new WebPush(options)
* option - object , see bellow
Parameter
Type
Default Value
Example
Description
swjsurl
string
''
/sw.js?v=${new Date() * 1}
格外的sw.js 需要项目方提供,这里是填 sw.js 路径
appid
string
''
''
系统标识
uid
number
''
''
用户标识
lang
string
''
'zh'
语言
online
string
''
number
在线状态,0:离线,1:在线
platform
number
1
1
1:Google
Methods
` js
wp = new WebPush(options)
`$3
注册service worker进程,若init时候没传applicationServerPublicKey,将会向webpush平台请求applicationServerPublicKey
` js
wp.init().then((resp) => {
// resp.code: 0 成功 非0 失败
// todo after init
})
`
$3
获取订阅状态$3
获取push key$3
订阅 需要传 push key$3
设置用户使用的语言` js
wp.subscribeUser(this.wp.getPushKey()).then(resp => {
console.log('after subscribeUser', resp)
if (resp.code === 0) {
this.isSubscribed = true
}
})
`
$3
取消订阅
` js
wp.unsubscribeUser().then(resp => {
console.log('after unsubscribeUser', resp)
if (resp.code === 0) {
this.isSubscribed = false
}
})
`$3
用户退出登录 解除绑定关系项目支持
项目本身要提供一个Service Worker 脚本,并把脚本地址在实例化WebPush类时候传入。Service Worker 内容可以是自定义的 或者参考如下:
`js
console.log('web push service worker init', self)
self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.')
console.log([Service Worker] Push had this data: "${event.data.text()}", self.registration)
const maxVisibleActions = Notification.maxActions
const title = event.data.text()
const options = {
body: 'test body',
icon: 'images/icon.png',
badge: 'images/badge.png',
'actions': [
{ 'action': 'yes', 'title': 'Yes', 'icon': 'images/icon.png' },
{ 'action': 'no', 'title': 'No', 'icon': 'images/icon.png' }
]
} if (maxVisibleActions < 4) {
options.body =
This notification will only display +
${maxVisibleActions} actions.
} else {
options.body = This notification can display up to +
${maxVisibleActions} actions.
}
const notificationPromise = self.registration.showNotification(title, options)
event.waitUntil(notificationPromise)
})self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.', event)
if (event.action === 'yes') {
event.notification.close()
console.log('click yes')
} else if (event.action === 'no') {
event.notification.close()
console.log('click no')
} else {
event.waitUntil(self.clients.openWindow('https://developers.google.com/web/'))
}
})
``js
self.importScripts('https://static.moschat.com/web_static/service-worker.js')
`相关资料
push companionnpm 发布
`
npm publish --access public
``