Skip to content

Commit

Permalink
Merge pull request #1507 from ruchamahabal/fix-sw-registration
Browse files Browse the repository at this point in the history
fix: decouple FCM initialization failures from service worker registrations
  • Loading branch information
ruchamahabal authored Mar 5, 2024
2 parents 6ca8cab + 1846d24 commit 77ec067
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 56 deletions.
32 changes: 22 additions & 10 deletions frontend/public/frappe-push-notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,17 @@ class FrappePushNotification {
if (this.webConfig !== null && this.webConfig !== undefined) {
return this.webConfig
}
let url = `${FrappePushNotification.relayServerBaseURL}/api/method/notification_relay.api.get_config?project_name=${this.projectName}`
let response = await fetch(url)
let response_json = await response.json()
this.webConfig = response_json.config
return this.webConfig
try {
let url = `${FrappePushNotification.relayServerBaseURL}/api/method/notification_relay.api.get_config?project_name=${this.projectName}`
let response = await fetch(url)
let response_json = await response.json()
this.webConfig = response_json.config
return this.webConfig
} catch (e) {
throw new Error(
"Push Notification Relay is not configured properly on your site."
)
}
}

/**
Expand All @@ -103,11 +109,17 @@ class FrappePushNotification {
if (this.vapidPublicKey !== "") {
return this.vapidPublicKey
}
let url = `${FrappePushNotification.relayServerBaseURL}/api/method/notification_relay.api.get_config?project_name=${this.projectName}`
let response = await fetch(url)
let response_json = await response.json()
this.vapidPublicKey = response_json.vapid_public_key
return this.vapidPublicKey
try {
let url = `${FrappePushNotification.relayServerBaseURL}/api/method/notification_relay.api.get_config?project_name=${this.projectName}`
let response = await fetch(url)
let response_json = await response.json()
this.vapidPublicKey = response_json.vapid_public_key
return this.vapidPublicKey
} catch (e) {
throw new Error(
"Push Notification Relay is not configured properly on your site."
)
}
}

/**
Expand Down
73 changes: 40 additions & 33 deletions frontend/public/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,47 +11,54 @@ precacheAndRoute(self.__WB_MANIFEST)
cleanupOutdatedCaches()

const jsonConfig = new URL(location).searchParams.get("config")
const firebaseApp = initializeApp(JSON.parse(jsonConfig))
const messaging = getMessaging(firebaseApp)

function isChrome() {
return navigator.userAgent.toLowerCase().includes("chrome")
}
// Firebase config initialization
try {
const firebaseApp = initializeApp(JSON.parse(jsonConfig))
const messaging = getMessaging(firebaseApp)

onBackgroundMessage(messaging, (payload) => {
const notificationTitle = payload.data.title
let notificationOptions = {
body: payload.data.body || "",
}
if (payload.data.notification_icon) {
notificationOptions["icon"] = payload.data.notification_icon
function isChrome() {
return navigator.userAgent.toLowerCase().includes("chrome")
}
if (isChrome()) {
notificationOptions["data"] = {
url: payload.data.click_action,

onBackgroundMessage(messaging, (payload) => {
const notificationTitle = payload.data.title
let notificationOptions = {
body: payload.data.body || "",
}
} else {
if (payload.data.click_action) {
notificationOptions["actions"] = [
{
action: payload.data.click_action,
title: "View Details",
},
]
if (payload.data.notification_icon) {
notificationOptions["icon"] = payload.data.notification_icon
}
}
self.registration.showNotification(notificationTitle, notificationOptions)
})

if (isChrome()) {
self.addEventListener("notificationclick", (event) => {
event.stopImmediatePropagation()
event.notification.close()
if (event.notification.data && event.notification.data.url) {
clients.openWindow(event.notification.data.url)
if (isChrome()) {
notificationOptions["data"] = {
url: payload.data.click_action,
}
} else {
if (payload.data.click_action) {
notificationOptions["actions"] = [
{
action: payload.data.click_action,
title: "View Details",
},
]
}
}
self.registration.showNotification(notificationTitle, notificationOptions)
})

if (isChrome()) {
self.addEventListener("notificationclick", (event) => {
event.stopImmediatePropagation()
event.notification.close()
if (event.notification.data && event.notification.data.url) {
clients.openWindow(event.notification.data.url)
}
})
}
} catch (error) {
console.log("Failed to initialize Firebase", error)
}

self.skipWaiting()
clientsClaim()
console.log("Service Worker Initialized")
36 changes: 23 additions & 13 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,28 +56,38 @@ app.provide("$employee", employeeResource)
app.provide("$socket", socket)
app.provide("$dayjs", dayjs)

const registerServiceWorker = () => {
const registerServiceWorker = async () => {
window.frappePushNotification = new FrappePushNotification("hrms")

if ("serviceWorker" in navigator) {
window.frappePushNotification
.appendConfigToServiceWorkerURL("/assets/hrms/frontend/sw.js")
.then((url) => {
navigator.serviceWorker
.register(url, {
type: "classic",
})
.then((registration) => {
window.frappePushNotification.initialize(registration).then(() => {
console.log("Frappe Push Notification initialized")
})
let serviceWorkerURL = "/assets/hrms/frontend/sw.js"
let config = ""

try {
config = await window.frappePushNotification.fetchWebConfig()
serviceWorkerURL = `${serviceWorkerURL}?config=${encodeURIComponent(
JSON.stringify(config)
)}`
} catch (err) {
console.error("Failed to fetch FCM config", err)
}

navigator.serviceWorker
.register(serviceWorkerURL, {
type: "classic",
})
.then((registration) => {
if (config) {
window.frappePushNotification.initialize(registration).then(() => {
console.log("Frappe Push Notification initialized")
})
}
})
.catch((err) => {
console.error("Failed to register service worker", err)
})
} else {
console.error("Service worker not enabled/supported by browser")
console.error("Service worker not enabled/supported by the browser")
}
}

Expand Down

0 comments on commit 77ec067

Please sign in to comment.