|
<html> |
|
|
|
<head> |
|
<script> |
|
const registerServiceWorker = async () => { |
|
if ('serviceWorker' in navigator) { |
|
try { |
|
const registration = await navigator.serviceWorker.register( |
|
'/firebase-messaging-sw.js', { |
|
scope: '/', |
|
} |
|
); |
|
if (registration.installing) { |
|
console.log('Service worker installing'); |
|
} else if (registration.waiting) { |
|
console.log('Service worker installed'); |
|
} else if (registration.active) { |
|
console.log('Service worker active'); |
|
} |
|
} catch (error) { |
|
console.error(`Registration failed with ${error}`); |
|
} |
|
} |
|
}; |
|
|
|
registerServiceWorker(); |
|
</script> |
|
</head> |
|
|
|
<body> |
|
|
|
<script type="module"> |
|
import { |
|
initializeApp |
|
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"; |
|
import { |
|
getAnalytics |
|
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-analytics.js"; |
|
import { |
|
getMessaging, |
|
getToken, |
|
onMessage |
|
} from "https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging.js"; |
|
|
|
const firebaseConfig = { |
|
... (the same used in the firebase-messaging-sw.js file) |
|
}; |
|
|
|
// Initialize Firebase |
|
const app = initializeApp(firebaseConfig); |
|
|
|
const messaging = getMessaging(app); |
|
|
|
getToken(messaging, { |
|
vapidKey: 'The web push certificate public key pair here (obtain from Project settings -> Cloud messaging)' |
|
}).then((currentToken) => { |
|
if (currentToken) { |
|
console.log(currentToken) |
|
} else { |
|
// Show permission request UI |
|
console.log('No registration token available. Requesting permission...'); |
|
} |
|
}).catch((err) => { |
|
console.log('An error occurred while retrieving token. ', err); |
|
}); |
|
|
|
onMessage(messaging, function(payload) { |
|
console.log( |
|
"[firebase-foreground] Received foreground message ", |
|
payload, |
|
); |
|
|
|
var notificationOptions = {}; |
|
|
|
if ("body" in payload.notification) { |
|
notificationOptions['body'] = payload.notification.body; |
|
} |
|
if ("icon" in payload.notification) { |
|
notificationOptions['icon'] = payload.notification.icon; |
|
} |
|
if ("image" in payload.notification) { |
|
notificationOptions['image'] = payload.notification.image; |
|
} |
|
|
|
var notif = new Notification(payload.notification.title, notificationOptions); |
|
|
|
if ("fcmOptions" in payload) { |
|
if ("link" in payload.fcmOptions) { |
|
notif.onclick = function() { |
|
window.open(payload.fcmOptions.link, '_blank').focus(); |
|
}; |
|
} |
|
} |
|
}); |
|
</script> |
|
</body> |
|
|
|
</html> |