Supporting platform-specific menus

While Electron provides a unified and convenient way to build application menus across platforms, there are still scenarios where you may want to tune the behavior or appearance of certain items based on the platform your users use.

An excellent example of a platform-specific rendering is a macOS deployment. If you are a macOS user, you already know that each application has a specific item that always goes first in the application menu. This menu item always has the same label as the application name, and it provides some application-specific facilities, such as quitting the running instance, navigating to preferences, often showing the About link, and so on.

Let's create a macOS-specific menu item that allows your users to see the About dialog and also quit the application:

  1. First of all, we need to fetch the name of the application somehow. You can do that by importing the app object from the Electron framework:
      const { app, Menu, shell } = require('electron');

The app object includes the getName method, which fetches the application name from the package.json file.

Of course, you can hardcode the name as a string, but it is much more convenient to get the value dynamically at runtime from the package configuration file. This allows us to keep a single centralized place for the application name and makes our code reusable across multiple applications.

Node.js exposes a global object called process, which provides access to environment variables. This object can also provide information about the current platform architecture. We are going to check this against the darwin value to detect the macOS platform.

  1. Append the following code right after the template declaration:
      if (process.platform === 'darwin') {
template.unshift({
label: app.getName(),
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'quit' }
]
})
}

As you can see, we check for the darwin string. In the case of an application running on macOS, a new menu entry is inserted at the beginning of the application menu.

For the time being, it is going to show Electron every time you run the npm start command, but don't worry—we are going to change that shortly:

The following options are available when you're checking for process architecture:

  • aix
  • darwin
  • freebsd
  • linux
  • openbsd
  • sunos
  • win32

Typically, you are going to check for darwin (macOS), linux (Ubuntu and other Linux systems), and win32 (Windows platforms).

For more details regarding process.platform, please refer to the following Node.js documentation: https://nodejs.org/api/process.html#process_process_platform.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.224.103