IT/Etc

React + PWA Tutorial (notifications,push)

Full~ day πŸ˜€ 2023. 6. 21. 16:04
728x90
λ°˜μ‘ν˜•

PWAλž€

ν”„λ‘œκ·Έλ ˆμ‹œλΈŒ μ›Ή μ•±(Progressive Web Apps)은 μ›Ή μ•±κ³Ό λ„€μ΄ν‹°λΈŒ μ•±μ˜ μž₯점을 λͺ¨λ‘ μ œκ³΅ν•˜λŠ”, 보닀 λ°œμ „λœ ν˜•νƒœμ˜ μ›Ή μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ„ μ–΄λ–»κ²Œ 개발 ν•  수 μžˆλŠ”κ°€μ— λŒ€ν•œ λ…Όμ˜μ΄μž 개발 철학을 λ§ν•œλ‹€.
Google I/O 2016μ—μ„œ 처음 μ†Œκ°œλ˜μ—ˆκ³  μ€„μ—¬μ„œ PWA라고 λΆ€λ₯Έλ‹€

 

Notifications

const randomNotification = () => {
    const notifTitle = "Title";
    const notifBody = "Body";
    const notifImg = imgUrl;
    const options = {
      body: notifBody,
      icon: notifImg,
    };
    new Notification(notifTitle, options);
    setTimeout(randomNotification, 30000);
 };

<Button
    id="notifications"
    onClick={() => {
      console.log(Notification.permission);
      if (!("Notification" in window)) {
        alert("not support notification ");
      } else if (Notification.permission === "granted") {
        randomNotification();
      } else if (Notification.permission !== "denied") {
        Notification.requestPermission().then((permission) => {
          if (permission === "granted") {
            const notification = new Notification("good!!");
          }
        });
      }
    }}
    >
    noti
</Button>

Button을 μƒμ„±ν•˜μ—¬ ν΄λ¦­μ‹œ μ•Œλ¦Όμ΄ λ‚˜νƒ€λ‚˜κ²Œ ν•˜λŠ” κΈ°λŠ₯μž…λ‹ˆλ‹€.

ν•œλ²ˆ μ‹€ν–‰λ˜λ©΄ 30μ΄ˆμ”© λ°˜λ³΅ν•˜μ—¬ μ‹€ν–‰λ˜λ„λ‘ μž‘μ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€.

μ•Œλ¦Όν‘œμ‹œ

 

 

Push

 

index.js

function urlBase64ToUint8Array(base64String) {
  var padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  var base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/");

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

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

navigator.serviceWorker.register("/service-worker.js");
navigator.serviceWorker.ready
  .then(function (registration) {
    return registration.pushManager.getSubscription().then(async function (subscription) {
      console.log(subscription, "subscription");
      if (subscription) {
        return subscription;
      }

      const response = await axios.post("/api/vapidPublicKey");
      const vapidPublicKey = response.data.data;
      const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);

      return registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: convertedVapidKey,
      });
    });
  })
  .then(function (subscription) {
    fetch("/api/register", {
      method: "post",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({
        subscription: subscription,
      }),
    });

    fetch("/api/sendNotification", {
      method: "post",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({
        subscription: subscription,
        delay: 1,
      }),
    });
  });

 

 

server.js

 

const webPush = require("web-push");
webPush.setVapidDetails("https://example.com/", process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY);

router.post(
  "/api/vapidPublicKey",
  asyncHandler(async (req, res, next) => {
   	res.send({data: process.env.VAPID_PUBLIC_KEY})
  })
);

router.post(
  "/api/register",
  asyncHandler(async (req, res, next) => {
   	res.send('')
  })
);

router.post(
  "/api/sendNotification",
  asyncHandler(async (req, res, next) => {
   	const payload = JSON.stringify({ title: "Push Test" });
    setTimeout(() => {
      webPush.sendNotification(subscription, payload).catch((err) => {
        console.log(err);
      });
    }, req.body.delay * 1000);
  })
);

μ΄λ ‡κ²Œ 보내진닀

μ°Έκ³ 

 

https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Tutorials/js13kGames/Re-engageable_Notifications_Push

 

How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs) | MDN

Having the ability to cache the contents of an app to work offline is a great feature. Allowing the user to install the web app on their home screen is even better. But instead of relying only on user actions, we can do more, using push messages and notifi

developer.mozilla.org

728x90
λ°˜μ‘ν˜•
LIST