Has anyone been able to get Web Push notifications to work on iOS? I have followed the blazor pizza example https://github.com/dotnet-presentations/blazor-workshop/blob/main/docs/09-progressive-web-app.md#sending-push-notifications and can get that to work for desktop. Note the tutorial only has you update the service-worker.js but if you publish the app you will also need to update the service-worker.publish.js. I am able on iOS to install the app as a PWA and it prompts me to allow notifications. I can even get a subscription:
url - https://web.push.apple.com/QL6zHJz733--fiTROuD0EEGfsi0hhs7RUdZFXzx...p256dh - BCZ+cL6Fy1BFiBLEgJNs2dbA6YzkSYyS... auth - HJd1....
Here is my service-worker.js
console.log('Installing service worker...');
self.skipWaiting();
});
self.addEventListener('fetch', event => {
// You can add custom logic here for controlling whether to use cached data if offline, etc.
// The following line opts out, so requests go directly to the network as usual.
return null;
});
self.addEventListener('push', event => {
const payload = event.data.json();
event.waitUntil(
self.registration.showNotification('MyApp', {
body: payload.message,
icon: 'icon-512.png',
vibrate: [100, 50, 100],
data: { url: payload.url }
})
);
});
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
service-worker.publish.js
// offline support. See https://aka.ms/blazor-offline-considerations
self.importScripts('./service-worker-assets.js');
self.addEventListener('install', event => event.waitUntil(onInstall(event)));
self.addEventListener('activate', event => event.waitUntil(onActivate(event)));
self.addEventListener('fetch', event => event.respondWith(onFetch(event)));
const cacheNamePrefix = 'offline-cache-';
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}`;
const offlineAssetsInclude = [ /\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/, /\.blat$/, /\.dat$/ ];
const offlineAssetsExclude = [ /^service-worker\.js$/ ];
// Replace with your base path if you are hosting on a subfolder. Ensure there is a trailing '/'.
const base = "/";
const baseUrl = new URL(base, self.origin);
const manifestUrlList = self.assetsManifest.assets.map(asset => new URL(asset.url, baseUrl).href);
async function onInstall(event) {
console.info('Service worker: Install');
// Fetch and cache all matching items from the assets manifest
const assetsRequests = self.assetsManifest.assets
.filter(asset => offlineAssetsInclude.some(pattern => pattern.test(asset.url)))
.filter(asset => !offlineAssetsExclude.some(pattern => pattern.test(asset.url)))
.map(asset => new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' }));
await caches.open(cacheName).then(cache => cache.addAll(assetsRequests));
}
async function onActivate(event) {
console.info('Service worker: Activate');
// Delete unused caches
const cacheKeys = await caches.keys();
await Promise.all(cacheKeys
.filter(key => key.startsWith(cacheNamePrefix) && key !== cacheName)
.map(key => caches.delete(key)));
}
async function onFetch(event) {
let cachedResponse = null;
if (event.request.method === 'GET') {
// For all navigation requests, try to serve index.html from cache,
// unless that request is for an offline resource.
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
const shouldServeIndexHtml = event.request.mode === 'navigate'
&& !manifestUrlList.some(url => url === event.request.url);
const request = shouldServeIndexHtml ? 'index.html' : event.request;
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
}
return cachedResponse || fetch(event.request);
}
self.addEventListener('push', event => {
const payload = event.data.json();
event.waitUntil(
self.registration.showNotification('MyApp', {
body: payload.message,
icon: 'icon-512.png',
vibrate: [100, 50, 100],
data: { url: payload.url }
})
);
});
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
On the server side i am using the https://github.com/web-push-libs/web-push-csharp library to send the notifications
var pushSubscription = new PushSubscription(webPushNotification.Url, webPushNotification.P256dh, webPushNotification.Auth);
var vapidDetails = new VapidDetails("mailto:<info@example.com>", publicKey, privateKey);
var webPushClient = new WebPushClient();
try
{
var payload = JsonConvert.SerializeObject(new
{
message = "MyApp Notification",
url = $"/",
});
await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error sending push notification: " + ex.Message);
}
I don't get an error sending the notification but it doesn't work with any subscriptions with https://web.push.apple.com/ Has anyone been able to do web push notification to https://web.push.apple.com/?
I was getting response code 403 from web.push.apple.com further investigation showed that my email was not formatted correctly on the jwt mailto:<info@example.com>
should be mailto:info@example.com
Credit https://developer.apple.com/documentation/usernotifications/sending_web_push_notifications_in_web_apps_and_browsers
BadJwtToken The JSON web token (JWT) has one of following issues: The JWT is missing. The JWT is signed with the wrong private key. The JWT subject claim isn’t a URL or mailto:. The JWT audience claim isn’t the origin of the push service where you sent the request. The JWT expiration parameter is more than one day into the future.