npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-push-api

v0.0.4

Published

Utility to subscribe/unsubscribe to Push API notifications and syncing with backend.

Downloads

8

Readme

Web Push API

The API for subscribing/unsubscribing to Push API notifications and optional syncing the subscription to your backend.

Installation

npm i --save web-push-api

Usage

Abstract example.

import { isSupported, getPushSubscriptionFlow, getPushSubscriptionPayload } from 'web-push-api';

if (isSupported) {
  getPushSubscriptionFlow((method, pushSubscription) => {
    sendRequestToBackend(method, getPushSubscriptionPayload(pushSubscription));
  });
}

React component

import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { isSupported, getPushSubscriptionFlow, getPushSubscriptionPayload } from 'web-push-api';

import Spinner from 'your-spinner-component';

const flow = !isSupported ? null : getPushSubscriptionFlow((method, pushSubscription) => {
  fetch('https://example.com/web-push-api/subscription', { method, body: getPushSubscriptionPayload(pushSubscription) })
    .then((response) => response.json())
    .then(({ errors }) => errors.map(showError))
    .catch(showError);
});

/**
 * @param {Error|string} error
 */
function showError(error) {
  alert(error instanceof Error ? error.message : error);
}

/**
 * @param {function(state: Object): void} updateState
 * @param {('getPermission'|'getSubscription'|'subscribe'|'unsubscribe')} method
 * @param {('permission'|'subscription')} affects
 * @param {string|null} valueOnError
 * @param {string} [applicationServerKey]
 */
function doFlowAction(updateState, method, affects, valueOnError, applicationServerKey) {
  (async () => {
    let value = valueOnError;

    try {
      value = await flow[method](applicationServerKey);
    } catch (error) {
      showError(error);
    }

    updateState({ processing: false, [affects]: value });
  })();
}

/**
 * @param {function(state: Object): void} updateState
 * @param {('subscribe'|'unsubscribe')} method
 * @param {string} [applicationServerKey]
 *
 * @return {function(event: Event): void}
 */
function getFlowActionHandler(updateState, method, applicationServerKey) {
  return (event) => {
    event.preventDefault();
    updateState({ processing: true });
    doFlowAction(updateState, method, 'subscription', null, applicationServerKey);
  };
}

function PushNotificationsSubscriber({ offline, applicationServerKey }) {
  const [{ permission, subscription, processing = true }, setState] = useState({});
  const updateState = (state) => setState((prevState) => ({ ...prevState, ...state }));
  let children;

  useEffect(() => {
    if (permission === undefined) {
      doFlowAction(updateState, 'getPermission', 'permission', 'denied');
    } else if (!offline && permission === 'granted' && subscription === undefined) {
      doFlowAction(updateState, 'getSubscription', 'subscription', null);
    }
  }, [offline, permission, subscription, updateState]);

  if (processing) {
    children = (
      <Spinner small />
    );
  } else if (permission !== 'granted' || offline) {
    const title = offline 
      ? 'This feature is not available since the app is offline. Please come back later.' 
      : 'Please turn notifications on. This will allow you receiving updates even if the application is closed.';

    children = (
      <span title={ title }>
        <i className="icon-notifications-off" />
      </span>
    );
  } else if (subscription === null) {
    children = (
      <button
        title="Click to subscribe to push notifications."
        onClick={ getFlowActionHandler(updateState, 'subscribe', applicationServerKey) }
      >
        <i className="icon-notifications-none" />
      </button>
    );
  } else {
    children = (
      <button
        title="Click to unsubscribe from push notifications."
        onClick={ getFlowActionHandler(updateState, 'unsubscribe') }
      >
        <i className="icon-notifications-active" />
      </button>
    );
  }

  return (
    <div className="push-notifications">
      { children }
    </div>
  );
}

PushNotificationsSubscriber.propTypes = {
  offline: PropTypes.bool.isRequired,
  applicationServerKey: PropTypes.string.isRequired,
};

export default flow ? PushNotificationsSubscriber : () => null;

Alternatives

  • https://github.com/dmitry-korolev/push-js