Skip to content

Instantly share code, notes, and snippets.

@megasmack
Created April 26, 2023 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megasmack/64f614d5f5c7dd1a83b148f6f843045c to your computer and use it in GitHub Desktop.
Save megasmack/64f614d5f5c7dd1a83b148f6f843045c to your computer and use it in GitHub Desktop.
LWC Browser Notifications
import { LightningElement } from 'lwc';
export default class BrowserNotificationsExample extends LightningElement {
connectedCallback() {
this.initPushNotifications();
}
// Modified from: https://levelup.gitconnected.com/creating-browser-notification-in-javascript-79e91bfb76c8
initPushNotifications() {
const { permission } = Notification;
if (permission === 'granted') {
this.showNotification();
} else if (permission === 'default') {
this.requestAndShowPermission();
}
}
showNotification() {
const title = 'Notification';
const icon = 'https://somewebsite.com/icon.svg';
const image = 'https://somewebsite.com/image.webp';
const body = 'Message to be displayed';
const notification = new Notification(title, { body, icon, image });
}
async requestAndShowPermission() {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
this.showNotification();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment