Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions app/javascript/controllers/notifications_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ export default class extends Controller {

switch(Notification.permission) {
case "default":
this.subscribeButtonTarget.hidden = false
this.explainerTarget.hidden = true
this.#showButtonToSubscribe()
break
case "granted":
const registration = await this.#getServiceWorkerRegistration()
const subscription = await registration?.pushManager?.getSubscription()

if (registration && subscription) {
this.element.classList.add(this.enabledClass)
} else {
this.#showButtonToSubscribe()
}
break
}
Expand Down Expand Up @@ -54,8 +55,9 @@ export default class extends Controller {
return navigator.serviceWorker.getRegistration("/service-worker.js", { scope: "/" })
}

#registerServiceWorker() {
return navigator.serviceWorker.register("/service-worker.js", { scope: "/" })
async #registerServiceWorker() {
await navigator.serviceWorker.register("/service-worker.js", { scope: "/" })
return navigator.serviceWorker.ready
}

async #subscribe(registration) {
Expand All @@ -76,6 +78,11 @@ export default class extends Controller {
}
}

#showButtonToSubscribe() {
this.subscribeButtonTarget.hidden = false
this.explainerTarget.hidden = true
}

async #requestPermissionAndSubscribe(registration) {
const permission = await Notification.requestPermission()
if (permission === "granted") this.#subscribe(registration)
Expand Down
2 changes: 1 addition & 1 deletion app/views/pwa/service_worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async function updateBadgeCount({ data: { badge } }) {
self.addEventListener("notificationclick", (event) => {
event.notification.close()

const url = new URL(event.notification.data.path, self.location.origin).href
const url = new URL(event.notification.data.url, self.location.origin).href
event.waitUntil(openURL(url))
})

Expand Down