Created
April 26, 2023 18:57
LWC Browser Notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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