2
votes

Comment pousser la notification Web en cliquant sur un bouton

Je m'entraîne donc à la notification Web et je suis tombé sur ce tutoriel https : //developers.google.com/web/fundamentals/codelabs/push-notifications/ Je ne comprends pas tout le code ici, mais j'essaye de le faire en l'essayant un par un, mais mon un problème est de savoir comment envoyer une notification Web par bouton?

Voici mon code:

index.html

'use strict';

self.addEventListener('push', function (event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

    const title = 'Push Codelab';
    const options = {
        body: 'Yay it works.',
        icon: 'images/icon.png',
        badge: 'images/badge.png'
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function (event) {
    console.log('[Service Worker] Notification click Received.');

    event.notification.close();

    event.waitUntil(
        clients.openWindow('https://developers.google.com/web/')
    );
});

main.js p>

'use strict';

const applicationServerPublicKey = 'BMpQ-7s56rTLKF7lR6wWQP9kKCbP3Q7Kidi96lHvREfmVV1mFtmSo08g_FuJ9vJkyGefboFo1Nj0JPlR2er9NLM';

const pushButton = document.querySelector('.js-push-btn');
const notifyButton = document.querySelector('#notify');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}

function initializeUI() {
  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}

function updateBtn() {
  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}

navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
  console.log('Service Worker is registered', swReg);

  swRegistration = swReg;
  initializeUI();
})

function initializeUI() {
  pushButton.addEventListener('click', function() {
    pushButton.disabled = true;
    if (isSubscribed) {
      // TODO: Unsubscribe user
    } else {
      subscribeUser();
    }
  });

  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}

function subscribeUser() {
  const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  })
  .then(function(subscription) {
    console.log('User is subscribed.');

    updateSubscriptionOnServer(subscription);

    isSubscribed = true;

    updateBtn();
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
    updateBtn();
  });
}

function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

  const subscriptionJson = document.querySelector('.js-subscription-json');
  const subscriptionDetails =
    document.querySelector('.js-subscription-details');

  if (subscription) {
    subscriptionJson.textContent = JSON.stringify(subscription);
    subscriptionDetails.classList.remove('is-invisible');
  } else {
    subscriptionDetails.classList.add('is-invisible');
  }
}

function updateBtn() {
  if (Notification.permission === 'denied') {
    pushButton.textContent = 'Push Messaging Blocked.';
    pushButton.disabled = true;
    updateSubscriptionOnServer(null);
    return;
  }

  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}

pushButton.addEventListener('click', function() {
  pushButton.disabled = true;
  if (isSubscribed) {
    unsubscribeUser();
  } else {
    subscribeUser();
  }
});

function unsubscribeUser() {
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    if (subscription) {
      return subscription.unsubscribe();
    }
  })
  .catch(function(error) {
    console.log('Error unsubscribing', error);
  })
  .then(function() {
    updateSubscriptionOnServer(null);

    console.log('User is unsubscribed.');
    isSubscribed = false;

    updateBtn();
  });
}

function unsubscribeUser() {
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    if (subscription) {
      return subscription.unsubscribe();
    }
  })
  .catch(function(error) {
    console.log('Error unsubscribing', error);
  })
  .then(function() {
    updateSubscriptionOnServer(null);

    console.log('User is unsubscribed.');
    isSubscribed = false;

    updateBtn();
  });
}

function pushNotification(){
    swRegistration.addEventListener('push', function (event) {
        console.log('[Service Worker] Push Received.');
        console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

        const title = 'Push Codelab';
        const options = {
            body: 'Yay it works.',
            icon: 'images/icon.png',
            badge: 'images/badge.png'
        };

        event.waitUntil(swRegistration.registration.showNotification(title, options));
    });

    swRegistration.addEventListener('notificationclick', function (event) {
        console.log('[Service Worker] Notification click Received.');

        event.notification.close();

        event.waitUntil(
            clients.openWindow('https://developers.google.com/web/')
        );
    });
}

notifyButton.addEventListener('click', function() {
    alert("alert");
    pushNotification();
})

sw.js

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Push Codelab</title>

  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css">
  <script defer src="https://code.getmdl.io/1.2.1/material.min.js"></script>
  <link rel="stylesheet" href="styles/index.css">
</head>

<body>

  <header>
    <h1>Push Codelab</h1>
  </header>

  <main>
    <p>Welcome to the push messaging codelab. The button below needs to be
    fixed to support subscribing to push.</p>
    <p>
      <button disabled class="js-push-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
        Enable Push Messaging
      </button>

      <button  class="js-push-btn mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" id="notify">
        Enable Push Messaging
      </button>
    </p>
    <section class="subscription-details js-subscription-details is-invisible">
      <p>Once you've subscribed your user, you'd send their subscription to your
      server to store in a database so that when you want to send a message
      you can lookup the subscription and send a message to it.</p>
      <p>To simplify things for this code lab copy the following details
      into the <a href="https://web-push-codelab.glitch.me//">Push Companion
      Site</a> and it'll send a push message for you, using the application
      server keys on the site - so make sure they match.</p>
      <pre><code class="js-subscription-json"></code></pre>
    </section>
  </main>

  <script src="scripts/main.js"></script>

  <script src="https://code.getmdl.io/1.2.1/material.min.js"></script>
</body>
</html>

comme vous pouvez le voir, j'ai ajouté une nouvelle fonction appelée pushNotification (); qui est utilisé lorsque le bouton de notification est cliqué, mais il n'enverra pas de notification. Y a-t-il un code plus simple à cela? Mon cerveau est déjà en train de s'effondrer.

Actuellement, je peux pousser la notification en accédant à mon mode développeurs> application> service worker le push. Mais je le veux par le bouton que j'ai créé.


0 commentaires

3 Réponses :


1
votes

Je pense que j'ai déjà la réponse, showNotification est tout ce dont j'ai besoin, pour tous ceux qui ont la même question, essayez ceci. A travaillé pour moi.

notifyButton.addEventListener('click', function() {
    const title = 'Simple Title';
    const options = {
      body: 'Simple piece of body text.\nSecond line of body text :)'
    };
    swRegistration.showNotification(title, options);
})


0 commentaires

0
votes

Habituellement, cette implémentation doit aller dans le fichier js du service worker, de sorte que tout push arrivant soit montré à l'utilisateur sans intervention manuelle requise par l'utilisateur final. self.registration. showNotification (...)

self.addEventListener('push', function (event) {
    if (!(self.Notification && self.Notification.permission === 'granted')) {
        return;
    }
    var data = {};
    if (event.data) {
        data = event.data.json();
    }
    console.log('Notification Received:');
    console.log(data);
    try {
        var title = data.title;
        var message = data.message;
        var url = data.data.url;
        var icon = "images/ns-logo.png";

        event.waitUntil(self.registration.showNotification(title, {
            body: message,
            icon: icon,
            badge: icon,
            data: url
        }));
    }
    catch (err) {
        console.log('Notification Processing Failed:', err);
    }
});


0 commentaires

0
votes

Assurez-vous que vous avez déjà enregistré sw.js et autorisez permission de notification du navigateur.

p> HTML

var btnnotify = document.querySelector('#ABCD');
btnnotify.addEventListener('click', function () {
   navigator.serviceWorker.getRegistration().then(sw => {
       let options = {
           body: "Let's buy some Nendoroid!",
           icon: "img/Sukusuku Hakutaku.png",
        };
   sw.showNotification("I want to buy a Nendoroid!", options);
   });

});

Votre JS

<button id="ABCD" class="btn btn-block">Notify</button>


0 commentaires