DEV Community

Cover image for Browser extensions - Adding browser notifications
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Browser extensions - Adding browser notifications

In this article, we'll be exploring how to add browser notifications to our browser extension.

As the starting point, I'll use our popup extension.
If you want to follow along, use the following GitHub repo.

The result of this article is the following interaction.

Browser extensions - Adding browser notifications

Adding browser notifications to a browser extensions

Browser notifications are native browsers that add notifications, much like you are used to on your mobile devices.

However, not many people opt-in for them at this stage. Let's hope this changes in the future.

For this article, we'll be using the popup extension to trigger a browser notification.

The first thing we'll have to do is give the correct permissions to our application.

Open up your manifest.json file and add the following permissions.

{
  "permissions": [
    "notifications"
  ]
}
Enter fullscreen mode Exit fullscreen mode

This will allow us to access the native notification layer.

Then we can open up our src/App.jsx file.
Let's add a button in the rendering part.

export function App() {
  return (
    <div className='flex flex-col items-center justify-center w-screen h-auto bg-indigo-400 p-4'>
      <button
        className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 text-2xl px-4 rounded'
        onClick={createNotification}
      >
        Surprise me πŸŽ‰
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

You might have spotted the createNotification on the click handler. Let's quickly add that function to our file.

const createNotification = () => {
  chrome.notifications.create({
    type: 'basic',
    iconUrl: 'icons/icon-48.png',
    title: 'Hi there πŸ‘‹',
    message: 'Just a reminder that you rock!',
    buttons: [{ title: 'I know ☺️' }],
    priority: 0,
  });
};
Enter fullscreen mode Exit fullscreen mode

This function calls the browser notification API and creates a new notification.
The notification will be called instantly.
We set a title, message, and custom button in our example.

Note: You can find all options in the documentation

Now let's build our app and see what happens.
Follow the guide here to build your app.

You should now see the notification occur!

Notification via browser extension

If you want to see the complete source code, I hosted it on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey, yes we can!
Check out this article I wrote a couple days ago:
daily-dev-tips.com/posts/browser-e...