concept notification in category electron

appears as: notifications, notification, notifications, notification
Electron in Action

This is an excerpt from Manning's book Electron in Action.

Support for notifications

Notifications work out of the box on macOS and Windows 10. They also work with the most common Linux desktop environment. Things get a bit tricky when working with older versions of Windows. This is beyond the scope of this book, but it is covered in the official documentation: http://mng.bz/nJR0.

This is the solution that we’re going with, but it’s not without its complications. Electron applications can create notifications using Chromium’s Notification API. As a web API, Notifications are available only in the renderer process and not in the main process.

To deliver this feature, we need to create a hidden BrowserWindow instance. When the user saves a new clipping using the global shortcut, we send a message via IPC to the renderer process. When the renderer process receives this message, it triggers the notification.

Let’s start by making an invisible process and then send messages to it and let it trigger the notifications. If you recall from Fire Sale, BrowserWindow instances can load HTML, which in turn can load JavaScript like a traditional web page would. The first thing we need is a bare minimum HTML page.

Listing 9.13. Setting up a simple HTML document: ./app/index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Clipmaster</title>
</head>

<body></body>

<script>
  require('./renderer');      #1
</script>

</html>

This page has some basic markup to make it a valid HTML page. The important part is that it contains a script tag that loads renderer.js, which contains the code that listens for messages from the main process and triggers the notification. Next, let’s set up that listener and write the code to display the notification.

Listing 9.14. Listening for messages and displaying notifications: ./app/renderer.js
const { ipcRenderer } = require('electron');

ipcRenderer.on('show-notification', (event, title, body) => {
  const myNotification = new Notification(title, { body });        #1
});

We pull in the ipcRenderer module and begin listening for notifications on the appropriately named show-notification channel. This listener expects three arguments in addition to the event object that is included by default: a title and body for the notification, as well as a function detailing what to do if the user clicks the notification. If no function is provided, onClick is an empty function by default.

Let’s start by tackling the alert that pops up whenever the user publishes a clipping. In its place, we display one of two notifications, shown in listing 10.19: that an error occurred with the message received from the server, or that the request was successful with the URL of the newly published clipping on ClipHub. If the request was successful, we add an event handler to the notification that opens ClipHub in their default browser when the user clicks the notification.

Listing 10.19. Setting up notifications when publishing a clipping: ./app/renderer.js
const { clipboard, shell } = require('electron');

// Code omitted for clarity...

const publishClipping = (clippingText) => {
  request.post({ json: { clipping } }), (error, response, body) => {
    if (error) {                                                      #1
      return new Notification('Error Publishing Your Clipping', {
        body: JSON.parse(error).message
      });
    }

    const url = body.url;
    const notification = new Notification(                            #2
      'Your Clipping Has Been Published',
      { body: `Click to open ${url} in your browser.` }
    );

    notification.onclick = () => { shell.openExternal(url); };        #3

    clipboard.writeText(url);
  };
};

To open a URL in the user’s default browser, we need to pull in the shell module from Electron. We’ll set the onclick method of the notification to an anonymous function that is triggered when the user clicks the notification.