Zenkie Bear

How to use Notification API

Intro

Notification API allows web application send a system-level notification.

Request Permission

Before sending notifications, your need to make sure your app has this permission. Let’s request notification permission~

Notification.requestPermission(status => {
  if ('granted' === status) {
    // sending
  }
})

Another form

const status = await Notification.requestPermission()
if ('granted' === status) {
  // sending
}

You can check the permission by straight reading Notification.permission.

  • “default”: Your application has not been granted yet, browser will prevent notification sending.
  • “granted”: User allows your app to sending notifications.
  • “denied”: User doesn’t allow your app to sending notification.

Send Notification

You could create a Notification object, and then browser will create a system-level notification.

if ('granted' === status) {
  const notify = new Notification('hi here')
}

The string hi there passed in construction is notificator’s title.

Options

The second optional parameter of Notification’s constructor is an options object. You can enrich your notification content through it.

const notify = new Notification('hi there', {
  body: 'I’m Zenkie Bear, thank you for visiting my blog.',
  icon: '/images/profile.jpg',
  data: {
    url: 'https://blog.zenkie.cn/',
    target: '_blank'
  }
})

Let me introduce these options for ya:

  • body: The description of notification.
  • icon: The icon of notification, you could provide an URL that point to an image.
  • data: It could be any data you wish to associate with the notification.
  • tag: You can add a tag to a new notification, if there’s already a same tag notification, the older will be closed.

There’re many useful options, you can refer to this document.

Event handle

Notification provides 4 events, you can listen to them and perform the tasks you want.

click event is the most commonly used. This example shows when user click the notification, open the url (which defined in the data) in a new tab.

const notify = new Notification('hi there', {
  data: {
    url: 'https://blog.zenkie.cn/',
    target: '_blank'
  }
})
// handle the click event.
notify.onclick = e => {
  const data = e.target.data
  window.open(data.url, data.target)
}

Another form is using addEventListener:

const notify = new Notification('hi there', {
  data: {
    url: 'https://blog.zenkie.cn/',
    target: '_blank'
  }
})
// handle the click event.
notify.addEventListener('click', e => {
  const data = e.target.data
  window.open(data.url, data.target)
})

Ending

That’s all, thank you for reading my article! You can find this article’s code in codepen.