Push
Subscribe the current service worker to web push messages, inspect the existing subscription and unsubscribe - the client half of the Web Push protocol, fully typed.
@inject Bit.Butil.Push pushMDN reference
web-push npm package or
WebPush NuGet package. This page demonstrates the client side only.
Returns true when the runtime exposes ServiceWorkerRegistration.pushManager. Chromium and Firefox support push broadly; Safari supports it from 16.1 on macOS, and on iOS only for web apps added to the Home Screen.
var supported = await push.IsSupported();Push subscriptions belong to a service worker registration. This button registers the demo /sw.js, whose push handler shows a notification with the received payload.
Bit.Butil.ServiceWorker serviceWorker
await serviceWorker.Register("/sw.js");Creates a push subscription for the active service worker. The applicationServerKey is your VAPID public key (base64-url encoded); generate a key pair once on your machine and keep the private key on your server. userVisibleOnly defaults to true because Chromium requires every push to result in a user-visible notification.
// Generate a VAPID key pair once (keep the private key server-side):
// npx web-push generate-vapid-keys
var sub = await push.Subscribe(applicationServerKey: "<your VAPID public key>");
// sub.IsActive, sub.Endpoint, sub.ExpirationTime, sub.P256dh, sub.AuthReturns the current subscription for the active service worker, or a payload with IsActive set to false when none exists. Send the Endpoint, P256dh and Auth values to your application server - that is everything it needs to push to this browser.
var sub = await push.GetSubscription();
if (sub.IsActive)
{
// persist sub.Endpoint, sub.P256dh and sub.Auth on your server
}Deactivates the active subscription and returns true when one was removed. Remember to also delete the subscription record from your application server, or it will keep pushing into the void.
var removed = await push.Unsubscribe();API reference
ValueTask<bool> IsSupported()ValueTask<PushSubscriptionInfo> GetSubscription()ValueTask<PushSubscriptionInfo> Subscribe(string applicationServerKey, bool userVisibleOnly = true)ValueTask<bool> Unsubscribe()bool IsActive { get; set; }string Endpoint { get; set; }long? ExpirationTime { get; set; }string P256dh { get; set; }string Auth { get; set; }