-
Notifications
You must be signed in to change notification settings - Fork 1
/
push.Notification.js
101 lines (79 loc) · 2.59 KB
/
push.Notification.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//server
const webpush = require('web-push');
// VAPID keys
const publicVapidKey = '<your public key here>';
const privateVapidKey = '<your private key here>';
webpush.setVapidDetails('mailto:[email protected]', publicVapidKey, privateVapidKey);
// Subscribe Route
app.post('/subscribe', (req, res) => {
// Get pushSubscription object
const subscription = req.body;
// Send 201 - resource created
res.status(201).json({});
// Create payload
const payload = JSON.stringify({ title: 'Push Test' });
// Pass object into sendNotification
webpush
.sendNotification(subscription, payload)
.catch(err => console.error(err));
});
// Client-side (React.js):
import { useEffect } from 'react';
function App() {
useEffect(() => {
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(registration => {
console.log('Service Worker registered');
})
.catch(err => console.log(`Service Worker error: ${err}`));
}
// Request for notification permission
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
subscribeUser();
}
});
}
}, []);
// Subscribe user
const subscribeUser = () => {
// Get service worker registration
navigator.serviceWorker.ready.then(registration => {
// Get push subscription object
registration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: '<your public key here>'
})
.then(subscription => {
// Send subscription object to server
fetch('/subscribe', {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'content-type': 'application/json'
}
});
});
});
};
return (
<div>
<h1>Push Notifications Example</h1>
</div>
);
}
export default App;
// Service worker (sw.js):
self.addEventListener('push', e => {
const data = e.data.json();
console.log('Push Received');
self.registration.showNotification(data.title, {
body: 'Notified by React App',
icon: '/src/icon.png'
});
});