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

  • Electron Projects
  • Denys Vuika
  • 414字
  • 2021-06-24 12:14:37

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.
主站蜘蛛池模板: 会昌县| 张北县| 平利县| 军事| 准格尔旗| 莒南县| 青阳县| 永和县| 天镇县| 民丰县| 师宗县| 山东省| 兖州市| 黑龙江省| 克拉玛依市| 德安县| 阳城县| 石阡县| 泸溪县| 准格尔旗| 竹山县| 西盟| 长兴县| 柏乡县| 枞阳县| 东乡族自治县| 依兰县| 乌兰县| 如皋市| 恩平市| 河北省| 沭阳县| 宁阳县| 大田县| 巩义市| 巴南区| 潮州市| 资阳市| 常宁市| 西乡县| 安西县|