From 1a26cacb66fae0d08023674062d095f9a2705414 Mon Sep 17 00:00:00 2001
From: BordedDev <>
Date: Mon, 7 Apr 2025 00:36:49 +0200
Subject: [PATCH] Fix up for push notifications on chrome
---
src/snek/static/push.js | 91 ++++++++++++++++++-------------
src/snek/static/service-worker.js | 26 ++++++++-
src/snek/templates/app.html | 1 +
src/snek/view/push.py | 2 +-
4 files changed, 79 insertions(+), 41 deletions(-)
diff --git a/src/snek/static/push.js b/src/snek/static/push.js
index c644210..f1089ae 100644
--- a/src/snek/static/push.js
+++ b/src/snek/static/push.js
@@ -11,44 +11,61 @@ function arrayBufferToBase64(buffer) {
const keyResponse = await fetch('/push.json')
const keyData = await keyResponse.json()
+console.log("Key data", keyData);
+
const publicKey = Uint8Array.from(atob(keyData.publicKey), c => c.charCodeAt(0))
-navigator.serviceWorker
- .register("/service-worker.js")
- .then((serviceWorkerRegistration) => {
- console.log(serviceWorkerRegistration);
- serviceWorkerRegistration.pushManager.subscribe({
- userVisibleOnly: true,
- applicationServerKey: publicKey,
- }).then(
- (pushSubscription) => {
- const subscriptionObject = {
- ...pushSubscription.toJSON(),
- encoding: PushManager.supportedContentEncodings,
- /* other app-specific data, such as user identity */
- };
- console.log(pushSubscription.endpoint, pushSubscription, pushSubscription.toJSON(), subscriptionObject);
- // The push subscription details needed by the application
- // server are now available, and can be sent to it using,
- // for example, the fetch() API.
+export const registerServiceWorker = async () => {
+ navigator.serviceWorker
+ .register("/service-worker.js")
+ .then((serviceWorkerRegistration) => {
+ console.log(serviceWorkerRegistration);
+ serviceWorkerRegistration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: publicKey,
+ }).then(
+ (pushSubscription) => {
+ const subscriptionObject = {
+ ...pushSubscription.toJSON(),
+ encoding: PushManager.supportedContentEncodings,
+ /* other app-specific data, such as user identity */
+ };
+ console.log(pushSubscription.endpoint, pushSubscription, pushSubscription.toJSON(), subscriptionObject);
+ // The push subscription details needed by the application
+ // server are now available, and can be sent to it using,
+ // for example, the fetch() API.
- fetch('/push.json', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(subscriptionObject),
- }).then((response) => {
- if (!response.ok) {
- throw new Error('Bad status code from server.');
- }
- return response.json();
- }).then((responseData) => {
- console.log(responseData);
- });
- },
- (error) => {
- console.error(error);
- },
- );
+ fetch('/push.json', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(subscriptionObject),
+ }).then((response) => {
+ if (!response.ok) {
+ throw new Error('Bad status code from server.');
+ }
+ return response.json();
+ }).then((responseData) => {
+ console.log(responseData);
+ });
+ },
+ (error) => {
+ console.error(error);
+ },
+ );
+ });
+}
+
+window.registerServiceWorker = () => {
+ return Notification.requestPermission().then((permission) => {
+ if (permission === "granted") {
+ return registerServiceWorker();
+ } else if (permission === "denied") {
+ console.log("Permission was denied");
+ } else {
+ console.log("Permission was dismissed");
+ }
});
+};
+registerServiceWorker().catch(console.error);
diff --git a/src/snek/static/service-worker.js b/src/snek/static/service-worker.js
index 05dd7af..be89157 100644
--- a/src/snek/static/service-worker.js
+++ b/src/snek/static/service-worker.js
@@ -7,7 +7,6 @@ async function requestNotificationPermission() {
async function subscribeUser() {
const registration =
await navigator.serviceWorker.register("/service-worker.js");
-
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY),
@@ -44,12 +43,15 @@ self.addEventListener("push", (event) => {
const message =
data.message || "Here's something you might want to check out.";
const icon = "images/new-notification.png";
+ console.log("showing message", title, message, icon);
- event.waitUntil(self.registration.showNotification(title, {
+ const reg = self.registration.showNotification(title, {
body: message,
tag: "simple-push-demo-notification",
icon,
- }));
+ }).then(e => console.log("success", e)).catch(console.error);
+
+ event.waitUntil(reg);
});
@@ -59,3 +61,21 @@ self.addEventListener("notificationclick", (event) => {
event.waitUntil(clients.openWindow(
"https://snek.molodetz.nl",));
});
+
+self.addEventListener("notificationclose", (event) => {
+
+})
+
+self.addEventListener("fetch", (event) => {
+ // console.log("Fetch event for ", event.request.url);
+ event.respondWith(
+ caches.match(event.request).then((response) => {
+ if (response) {
+ // console.log("Found response in cache: ", response);
+ return response;
+ }
+ // console.log("No response found in cache. About to fetch from network...");
+ return fetch(event.request);
+ })
+ );
+})
\ No newline at end of file
diff --git a/src/snek/templates/app.html b/src/snek/templates/app.html
index ba9d0d1..c27b803 100644
--- a/src/snek/templates/app.html
+++ b/src/snek/templates/app.html
@@ -41,6 +41,7 @@
📥
👥
⚙️
+ ✉️
🔒
diff --git a/src/snek/view/push.py b/src/snek/view/push.py
index db931e1..0dcae89 100644
--- a/src/snek/view/push.py
+++ b/src/snek/view/push.py
@@ -65,7 +65,7 @@ class PushView(BaseFormView):
print(body)
notifications =get_notifications()
- cert = base64.b64encode(
+ cert = base64.urlsafe_b64encode(
notifications.public_key.public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.UncompressedPoint