官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 郧西县| 广宗县| 东乡族自治县| 正蓝旗| 铁力市| 宁国市| 尤溪县| 海安县| 盐山县| 河北区| 疏附县| 通道| 开阳县| 汨罗市| 南靖县| 青海省| 马边| 龙陵县| 乾安县| 永平县| 莱芜市| 涿州市| 京山县| 土默特左旗| 白河县| 呼和浩特市| 沅陵县| 大石桥市| 青龙| 新巴尔虎左旗| 军事| 崇信县| 休宁县| 册亨县| 阳曲县| 郎溪县| 开封县| 贵溪市| 张家界市| 都江堰市| 若羌县|