Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

push notification - WebPush using Service Worker - pushManager.subscribe multiple applicationServerKey at a time

I am working on WebPush using Service Worker and web-push-php. I want to send push notifications from 2 different servers. They have 2 different applicationServerKey. Here is my code.....

//main file
///==================
const requestNotificationPermission = async () => {
    window.Notification.requestPermission().then(expr=>{
        console.log(expr); //granted
    });
}

const registerServiceWorker = async () => {
    const swRegistration = await navigator.serviceWorker.register('/sw.js');
    return swRegistration;
}
const main = async () => {
    check();
    const swRegistration = await registerServiceWorker();
    const permission =  await requestNotificationPermission();
}
main();


////sw.js
///==================
self.addEventListener('activate', async () => {
    var applicationServerKey = urlB64ToUint8Array('SERVER 1 PUBLIC KEY')
    const subscription = await self.registration.pushManager.subscribe({
        applicationServerKey:applicationServerKey,
        userVisibleOnly: true
    })
    console.log(JSON.stringify(subscription))

    //I want to register another server key 
    // var applicationServerKey2 = urlB64ToUint8Array('SERVER 2 PUBLIC KEY')
    // const subscription2 = await self.registration.pushManager.subscribe({
    //     applicationServerKey:applicationServerKey2,
    //     userVisibleOnly: true
    // })
    // console.log(JSON.stringify(subscription2))

});

self.addEventListener('push', event => {
    var payload = event.data.text();
    console.log('Received Data', event.data.text())
    var options = {
            body: payload,
    };
    event.waitUntil(self.registration.showNotification('Notification Testing', options));
});

Everything working fine, when I am just using only SERVER 1 KEY. But when I am trying to subscribe another server key, it says A subscription with a different applicationServerKey already exists. Is there any way to subscribe 2 different server's applicationServerKey?

question from:https://stackoverflow.com/questions/65904161/webpush-using-service-worker-pushmanager-subscribe-multiple-applicationserverk

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...