Simple way to subscribe to push notifications from your dApp.
Possible use-cases include:
- Get notified when DAO creates a new proposal or executes one
- Receive updates when tokens are transfered to or from an address
- When someone mints and NFT
- Engage with users in your game
- Or just simply when a transaction has finished.
Uses web-native push notifications (https://web.dev/push-notifications-overview) to display notifications in your browser (desktop or mobile).
Demo: https://webpush-two.vercel.app
Work in progress. Please reach out if you want to implement in your dApp!
yarn add @webpush.eth/react
// public/sw.js
// Listen for incoming push events
self.addEventListener("push", function (e) {
const { event, payload } = e.data ? e.data.json() : {};
// Select template
const { title, body } = templates({ event, payload });
// Show notification
e.waitUntil(self.registration.showNotification(title, { body }));
});
// Describe templates
const templates = ({ event, payload }) => {
const map = {
Transfer: (p) =>
`You have received ${p.amount._hex / 1e18} LINK from ${p.from}`,
};
return map[event](payload) || { title: event, body: JSON.stringify(payload) };
};
// src/App.tsx
import { WebPushProvider } from "@webpush.eth/react";
function App() {
return (
<WebPushProvider worker="./sw.js">
<SubscribeToPush />
</WebPushProvider>
);
}
import { useRegisterPush, useSubscribe } from "@webpush.eth/react";
function SubscribeToPush() {
const approve = useRegisterPush();
const subscribe = useSubscribe();
return (
<Button
isLoading={approve.isLoading || subscribe.isLoading}
onClick={async () => {
// Trigger approval of push notifications
approve.mutate().then(() =>
// Subscribe to event
subscribe.mutate({
// Contract address
address: "0x...",
// Contract event to subscribe to
event: "Transfer",
// Contract ABI (or fragment of it)
abi: [
"event Transfer(address indexed from, address indexed to, uint amount)",
],
// Arguments for event
args: [null, "0x..."],
})
);
}}
>
Subscribe to Push notifications
</Button>
);
}
- Support in iPhone not ready?
- Brave browsers deny Vapid host from google