Improved push subscription change event

This commit is contained in:
Eduard Urbach 2019-11-20 17:27:50 +09:00
parent 2d139e6381
commit 3a3867cc21
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
2 changed files with 43 additions and 31 deletions

View File

@ -273,40 +273,47 @@ function onPush(evt: PushEvent) {
})
}
function onPushSubscriptionChange(evt: any) {
return self.registration.pushManager.subscribe(evt.oldSubscription.options)
.then(async subscription => {
console.log("send subscription to server...")
async function onPushSubscriptionChange(evt: PushSubscriptionChangeEvent) {
const userResponse = await fetch("/api/me", {credentials: "same-origin"})
const user = await userResponse.json()
const rawKey = subscription.getKey("p256dh")
const key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ""
const rawSecret = subscription.getKey("auth")
const secret = rawSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawSecret))) : ""
const endpoint = subscription.endpoint
const pushSubscription = {
endpoint,
p256dh: key,
auth: secret,
platform: navigator.platform,
userAgent: navigator.userAgent,
screen: {
width: window.screen.width,
height: window.screen.height
}
}
const response = await fetch("/api/me", {credentials: "same-origin"})
const user = await response.json()
return fetch("/api/pushsubscriptions/" + user.id + "/add", {
method: "POST",
credentials: "same-origin",
body: JSON.stringify(pushSubscription)
await fetch(`/api/pushsubscriptions/${user.id}/remove`, {
method: "POST",
credentials: "same-origin",
body: JSON.stringify({
endpoint: evt.oldSubscription.endpoint
})
})
const subscription = evt.newSubscription || await self.registration.pushManager.subscribe(evt.oldSubscription.options)
if(!subscription || !subscription.endpoint) {
return
}
const rawKey = subscription.getKey("p256dh")
const key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ""
const rawSecret = subscription.getKey("auth")
const secret = rawSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawSecret))) : ""
const pushSubscription = {
endpoint: subscription.endpoint,
p256dh: key,
auth: secret,
platform: navigator.platform,
userAgent: navigator.userAgent,
screen: {
width: window.screen.width,
height: window.screen.height
}
}
await fetch(`/api/pushsubscriptions/${user.id}/add`, {
method: "POST",
credentials: "same-origin",
body: JSON.stringify(pushSubscription)
})
}
// onNotificationClick is called when the user clicks on a notification.

View File

@ -484,6 +484,11 @@ interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData;
}
interface PushSubscriptionChangeEvent extends ExtendableEvent {
readonly newSubscription: PushSubscription;
readonly oldSubscription: PushSubscription;
}
interface ServiceWorkerContainerEventMap {
"error": ErrorEvent;
"controllerchange": Event;