Skip to content

Instantly share code, notes, and snippets.

View Spyna's full-sized avatar
💭
🚀

Lorenzo Spinelli Spyna

💭
🚀
View GitHub Profile
@Spyna
Spyna / service-worker.js
Last active August 26, 2019 15:39
How to receive a web push notification i a service worker
function receivePushNotification(event) {
console.log("[Service Worker] Push Received.");
//const { image, tag, url, title, text } = event.data.json();
const notificationText = event.data.text();
const title = "A brand new notification!"
const options = {
//data: url,
data: "something you want to send within the notification, such an URL to open"
@Spyna
Spyna / service-worker.js
Created August 26, 2019 15:39
How to open a web push notification
function openPushNotification(event) {
console.log("[Service Worker] Notification click Received.", event.notification.data);
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data));
}
self.addEventListener("notificationclick", openPushNotification);
@Spyna
Spyna / push-notifications.js
Created August 29, 2019 15:13
Push notification manager
const pushServerPublicKey = "BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8";
/**
* checks if Push notification and service workers are supported by your browser
*/
function isPushNotificationSupported() {
return "serviceWorker" in navigator && "PushManager" in window;
}
/**
@Spyna
Spyna / sw.js
Created August 29, 2019 15:14
Full service worker to manage Push notifications
function receivePushNotification(event) {
console.log("[Service Worker] Push Received.");
const { image, tag, url, title, text } = event.data.json();
const options = {
data: url,
body: text,
icon: image,
vibrate: [200, 100, 200],
@Spyna
Spyna / usePushNotification.js
Last active November 14, 2024 12:14
React custom Hook to handle push notification
import { useState, useEffect } from "react";
import http from "./utils/http";
//the function to call the push server: https://github.com/Spyna/push-notification-demo/blob/master/front-end-react/src/utils/http.js
import {
isPushNotificationSupported,
askUserPermission,
registerServiceWorker,
createNotificationSubscription,
getUserSubscription
@Spyna
Spyna / PushNotificationComponent.js
Created August 30, 2019 07:52
A React Component that uses the usePushNotificationHook
import React from "react";
import usePushNotifications from "./usePushNotifications";
export default function PushNotificationDemo() {
const {
userConsent,
pushNotificationSupported,
userSubscription,
onClickAskUserPermission,
onClickSusbribeToPushNotification,