jpush.js
3.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { updateJpush } from '@/api/jpush'
import { platform } from '@/config/index'
import { ref, reactive, onMounted } from 'vue';
export function useJPush() {
const JPushModule = uni.requireNativePlugin('JG-JPush')
console.log('jpushModule', JPushModule)
const isRegistrationPushed = ref(false)
const registerID = ref(null)
const startUploadJpush = () => {
if (registerID.value) {
console.log(`推送注册成功222222${registerID.value}`)
isRegistrationPushed.value = true
console.log(222222, registerID.value)
// JPushModule.initJPushService()
// 监听通知点击事件 - 这是关键
JPushModule.addNotificationListener(result => {
console.log('通知事件回调:', result)
// 判断事件类型
if (result.notificationEventType === 'notificationOpened') {
// 用户点击了通知
console.log('用户点击了通知')
console.log('通知内容:', result)
// 获取自定义数据
if (result.extras) {
console.log('自定义数据:', result.extras)
// 根据自定义数据跳转页面
handleNotificationClick(result.extras)
}
} else if (result.notificationEventType === 'notificationArrived') {
// 通知到达
console.log('收到新通知')
}
})
// 监听自定义消息(透传消息)
JPushModule.addCustomMessageListener(result => {
console.log('收到自定义消息:', result)
})
// 监听本地通知点击
JPushModule.addLocalNotificationListener(result => {
console.log('本地通知被点击:', result)
})
updateJpush({ registrationId: registerID.value, platform: platform() })
.then(() => {
console.warn('推送注册成功')
// tip.showToast(`推送注册成功${registerID.value}`)
isRegistrationPushed.value = true
})
.catch((err) => {
console.error('调用推送接口失败', err)
// tip.showToast(`推送注册失败:${err}`)
})
}
}
const registerPush = () => {
if (isRegistrationPushed.value) {
return
}
if (registerID.value) {
// 调用接口后台关联
startUploadJpush()
return
}
try {
JPushModule.getRegistrationID((result) => {
registerID.value = result.registerID
console.warn('推送注册结果:', result)
// tip.showToast(`推送注册结果:${registerID.value}`)
startUploadJpush()
})
}
catch (err) {
console.error('推送注册异常', err)
// tip.showToast(`推送注册异常 :${err}`)
}
// 可能registerPush异常失败,再重试一次
setTimeout(() => {
registerPush()
}, 5000)
}
const checkNotificationAuthorization = () => {
JPushModule.isNotificationEnabled((result) => {
const code = result.code
if (code !== 1) {
uni.showToast({
icon: 'none',
title: '还没有通知权限,请在系统设置中开启',
duration: 3000,
})
JPushModule.openSettingsForNotification((result) => {
console.warn('打开通知设置结果:', result)
if (result.code === 1) {
// 用户已授权
registerPush()
}
else {
// 用户未授权
uni.showToast({
icon: 'none',
title: '您还没有打开通知权限',
duration: 3000,
})
}
})
}
})
JPushModule.requestPermission()
}
return {
JPushModule,
isRegistrationPushed,
registerID,
registerPush,
checkNotificationAuthorization,
}
}