Home > Web Front-end > JS Tutorial > Web Push Notifications with React and Pushpad

Web Push Notifications with React and Pushpad

Linda Hamilton
Release: 2025-01-23 18:49:11
Original
880 people have browsed it

Web Push Notifications with React and Pushpad

This tutorial demonstrates how to seamlessly integrate web push notifications into your React application using the Pushpad SDK. We'll create a simple React component: a button that enables users to subscribe to or unsubscribe from push notifications.

Setting up the Pushpad JavaScript SDK

Begin by adding a service-worker.js file to your website's root directory. Add the following code to this file:

<code class="language-javascript">importScripts('https://pushpad.xyz/service-worker.js');</code>
Copy after login

Next, include this code snippet in your website:

<code class="language-javascript">(function(p,u,s,h,x){p.pushpad=p.pushpad||function(){(p.pushpad.q=p.pushpad.q||[]).push(arguments)};h=u.getElementsByTagName('head')[0];x=u.createElement('script');x.async=1;x.src=s;h.appendChild(x);})(window,document,'https://pushpad.xyz/pushpad.js');

pushpad('init', PROJECT_ID);</code>
Copy after login

Remember to replace PROJECT_ID with your actual project ID from the Pushpad dashboard.

Note: Pushpad's init function attempts to register service-worker.js. If you've already registered a service worker, you can bypass this by using: pushpad('init', PROJECT_ID, { serviceWorkerPath: null });.

Pushpad SDK Functions

The Pushpad SDK provides several useful functions:

  • pushpad('subscribe'): Subscribes the user and displays the browser's permission prompt.
  • pushpad('status'): Retrieves the current subscription status.
  • pushpad('unsubscribe'): Unsubscribes the user.
  • pushpad('uid'): Authenticates users.
  • pushpad('tags'): Adds targeting data.

React Component: A Subscribe/Unsubscribe Button

Here's the React code for creating a subscribe/unsubscribe button:

<code class="language-javascript">import React, { useState, useEffect } from 'react';

const PushSubscriptionButton = () => {
  const [subscribed, setSubscribed] = useState(null);

  useEffect(() => {
    pushpad('status', (isSubscribed) => {
      setSubscribed(isSubscribed);
    });
  }, []);

  const subscribe = () => {
    pushpad('subscribe', (isSubscribed) => {
      setSubscribed(isSubscribed);
      if (!isSubscribed) {
        alert('Notifications are blocked by browser settings.');
      }
    });
  };

  const unsubscribe = () => {
    pushpad('unsubscribe', () => {
      setSubscribed(false);
    });
  };

  if (subscribed === null) {
    return null;
  }

  return (
    subscribed ? (
      <button onClick={unsubscribe}>Unsubscribe</button>
    ) : (
      <button onClick={subscribe}>Subscribe</button>
    )
  );
};

export default PushSubscriptionButton;</code>
Copy after login

This component checks the subscription status, displays the appropriate button ("Subscribe" or "Unsubscribe"), and handles subscription/unsubscription actions. It also provides a user-friendly alert if notifications are blocked.

Sending Notifications

Once you have subscribers, you can send notifications using the Pushpad dashboard (manual sending) or programmatically via the Pushpad API (using their Node.js or other language libraries). This allows you to send notifications even when users aren't actively on your website. Examples include new blog post announcements or e-commerce promotions.

The above is the detailed content of Web Push Notifications with React and Pushpad. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template