web-push-libs / web-push

Web Push library for Node.js
Other
3.26k stars 305 forks source link

How can I know my 'auth' and 'p256dh' keys. #715

Open x9nico opened 2 years ago

x9nico commented 2 years ago

Hello, I'm not understanding how can I know my auth and p256dh keys. Any ideas?

kosso commented 2 years ago

This information is returned by subscribe() after a user Allows Notifications.


async function subscribe() {
    let sw = await navigator.serviceWorker.ready;
    console.log('ServiceWorker', sw);
    let subscription = await sw.pushManager.subscribe({
        userVisibleOnly: true,
        // applicationServerKey is obtained from a server-side call to web-push `generateVAPIDKeys()`
        applicationServerKey: '<PUBLIC_VAPID_KEY>' 
    });

    // Be sure to JSON.stringify the result, or you won't see the keys in the console.

    console.log(JSON.stringify(subscription));
    // store this in a database etc. for you to be able to send messages to the user. later

    // For testing, I add it to the web page for copy/paste testing purposes on the sever side, since the console will ellipsify/shorten the long endpoint URL
    const p = document.createElement("p");
    p.appendChild(document.createTextNode(JSON.stringify(subscription)));
    document.querySelector("html").appendChild(p);

}