Readme

Push Notification Sender

This val can be used in other vals to send notifications to a segment using OneSignal's REST API

This is really handy if you want to send push notifications to your phone without building a native app! I built a barebones React PWA that asks for a password then loads the OneSignal Web SDK that I deployed to Netlify for free. OneSignal has easy to follow docs so you can build this functionality into a React, Angular, Vue app or even Wordpress! Then install the PWA on your platform of choice and you're off to the races!

Setup

  1. Save your ONESIGNAL_TOKEN and SEGMENT_APPID from OneSignal to your Val Town environment variables

  2. Import into another val!

import sendNotification from "https://esm.town/v/gwoods22/sendNotification";

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import axios from "npm:axios@1.7.7";
import * as cheerio from "npm:cheerio@1.0.0";
const onesignalToken = Deno.env.get("ONESIGNAL_TOKEN");
const segmentAppID = Deno.env.get("SEGMENT_APPID");
const defaultSegment = [Deno.env.get("DEFAULT_ONESIGNAL_SEGMENT")];
const onesignalURL = "https://onesignal.com/api/v1/notifications";
/**
* Send a notification to OneSignal
*
* @param heading - Main heading of the notification
* @param message - Notification body text
* @param url - Optional url to attach to the notifications
*/
export default async (heading: string, message, url = "", segment = defaultSegment) => {
const body = {
app_id: segmentAppID,
included_segments: segment,
headings: { en: heading },
contents: { en: message },
web_url: url,
};
const auth = {
headers: {
Authorization: `Basic ${onesignalToken}`,
},
};
try {
await axios.post(onesignalURL, body, auth);
} catch (error) {
console.error(error.response["data"]["errors"]);
throw error;
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
September 6, 2024