建立 Service Worker Web Push Notification — (Web Notification 實作紀錄)

const path = require('path');
const express = require('express');
const app = express();
app.use('/js', express.static(path.resolve(__dirname, '../js')));
app.get('/', (req, res) => {
res.send(`
<html>
<head></head>
<body>
<h1>Push Notification</h1>
<script src='js/main.js'></script>
</body>
</html>
`);
});
app.listen(8998);
建立檔案與資料夾
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
} else {
console.log('Push is not supported');
}
Service Worker and Push is supported
let swRegistration;
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker
.register('/js/sw.js')
.then(swReg => {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(err => console.log('Service Worker register error.'));
} else {
console.log('Push is not supported');
}
Service Worker is registered
Application > Service Worker
const applicationServerPublicKey =
'BPa8duHWL0iVFQHCx6CqInD1vZSUgQ0eCKPHmh6y4OFr_BLS6MOBWjig-RriDqZUTpU4KHwLTDlT5Cktqle1YyQ';
const applicationServerPublicKey =
'BPa8duHWL0iVFQHCx6CqInD1vZSUgQ0eCKPHmh6y4OFr_BLS6MOBWjig-RriDqZUTpU4KHwLTDlT5Cktqle1YyQ';
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker
.register('/js/sw.js')
.then(swReg => {
let swRegistration = swReg;
console.log('Service Worker is registered', swReg);
return Promise.resolve(swRegistration);
})
.then(swRegistration => inititalUI(swRegistration))
.catch(err => console.log('Service Worker register error.'));
} else {
console.log('Push is not supported');
}
function inititalUI(swRegistration) {
swRegistration.pushManager.getSubscription().then(subscription => {
let isSubscription = !(subscription === null);
if (isSubscription) {
console.log('User is subscribed.');
} else {
console.log('User is not subscribed.');
}
});
}
User is not subscribed.
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function subscribeUser(swRegistration) {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey
})
.then(subscription => {
console.log('User is subscribe.');
})
.catch(err => console.log('Failed to subscribe the user: ', err));
}
呼叫 subscribeUser
const SW = '[Service Worker]';
self.addEventListener('push', event => {
console.log(`${SW} Push Received.`);
console.log(`${SW} Push had this data: ${event.data.text()}`);
});
const SW = '[Service Worker]';
self.addEventListener('push', event => {
console.log(`${SW} Push Received.`);
console.log(`${SW} Push had this data: ${event.data.text()}`);
const title = '推送好消息';
const options = {
body: '好消息報報'
// icon: '',
// badge: ''
};
setTimeout(() => {
event.waitUntil(self.registration.showNotification(title, options));
}, 5000);
});
Service Worker Web Push Notification
self.addEventListener('notificationclick', event => {
console.log(`${SW} Notification click Received.`);
event.notification.close(); event.waitUntil(
clients.openWindow(
'https://developers.google.com/web/fundamentals/getting- started/codelabs/push-notifications/'
)
);
});

--

--

--

遨遊在硬體與軟體世界中,對於計算機一切事物都充滿好奇及熱情。

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Whien

Whien

遨遊在硬體與軟體世界中,對於計算機一切事物都充滿好奇及熱情。

More from Medium

Push messages to browser notifications

Adding TypeORM with sql.js to a Vite & Capacitor application

Firebase Cloud Functions ~ Migrating an Existing JavaScript Project to TypeScript

How to write tests for Redux Reducers in React.js/Next.js Apps!