app
控制你应用的事件生命周期。
进程:主进程
🌐 Process: Main
以下示例显示了如何在最后一个窗口关闭时退出应用:
🌐 The following example shows how to quit the application when the last window is closed:
const { app } = require('electron')
app.on('window-all-closed', () => {
app.quit()
})
事件
🌐 Events
app 对象会触发以下事件:
🌐 The app object emits the following events:
Event: 'will-finish-launching'
当应用完成基本启动时触发。在 Windows 和 Linux 上,will-finish-launching 事件与 ready 事件相同;在 macOS 上,该事件表示 NSApplication 的 applicationWillFinishLaunching 通知。
🌐 Emitted when the application has finished basic startup. On Windows and Linux,
the will-finish-launching event is the same as the ready event; on macOS,
this event represents the applicationWillFinishLaunching notification of
NSApplication.
在大多数情况下,你应该在 ready 事件处理程序中完成所有操作。
🌐 In most cases, you should do everything in the ready event handler.
Event: 'ready'
返回:
🌐 Returns:
event活动- “launchInfo”唱片<string, any> |[通知回复](structures/notification-response.md) macOS
在 Electron 完成初始化时触发一次。在 macOS 上,launchInfo 包含打开应用时使用的 NSUserNotification 的 userInfo 或 UNNotificationResponse 的信息(如果应用是从通知中心启动的)。你也可以调用 app.isReady() 来检查该事件是否已触发,以及调用 app.whenReady() 来获取一个在 Electron 初始化完成时会被兑现的 Promise。
🌐 Emitted once, when Electron has finished initializing. On macOS, launchInfo
holds the userInfo of the NSUserNotification
or information from UNNotificationResponse
that was used to open the application, if it was launched from Notification Center.
You can also call app.isReady() to check if this event has already fired and app.whenReady()
to get a Promise that is fulfilled when Electron is initialized.
ready 事件只会在主进程完成事件循环的第一次执行后触发。如果需要在 ready 事件之前调用 Electron API,请确保在主进程的顶层上下文中同步调用它。
Event: 'window-all-closed'
当所有窗口都关闭时发出。
🌐 Emitted when all windows have been closed.
如果你没有订阅此事件并且所有窗口都已关闭,则默认行为是退出应用;但是,如果你订阅了该事件,你可以控制应用是否退出。如果用户按下 Cmd + Q,或者开发者调用了 app.quit(),Electron 会首先尝试关闭所有窗口,然后触发 will-quit 事件,在这种情况下 window-all-closed 事件将不会被触发。
🌐 If you do not subscribe to this event and all windows are closed, the default
behavior is to quit the app; however, if you subscribe, you control whether the
app quits or not. If the user pressed Cmd + Q, or the developer called
app.quit(), Electron will first try to close all the windows and then emit the
will-quit event, and in this case the window-all-closed event would not be
emitted.
Event: 'before-quit'
返回:
🌐 Returns:
event活动
在应用开始关闭其窗口之前发出。调用 event.preventDefault() 将阻止默认行为,即终止应用。
🌐 Emitted before the application starts closing its windows.
Calling event.preventDefault() will prevent the default behavior, which is
terminating the application.
如果应用退出是由 autoUpdater.quitAndInstall() 发起的,
则在对所有窗口发出 close 事件并关闭它们之后,会发出 before-quit。
在 Windows 上,如果应用因系统关机/重启或用户注销而关闭,则不会触发此事件。
Event: 'will-quit'
返回:
🌐 Returns:
event活动
当所有窗口都已关闭且应用即将退出时触发。调用 event.preventDefault() 将阻止默认行为,即终止应用。
🌐 Emitted when all windows have been closed and the application will quit.
Calling event.preventDefault() will prevent the default behavior, which is
terminating the application.
请参阅 window-all-closed 事件的描述,以了解 will-quit 和 window-all-closed 事件之间的差异。
🌐 See the description of the window-all-closed event for the differences between
the will-quit and window-all-closed events.
在 Windows 上,如果应用因系统关机/重启或用户注销而关闭,则不会触发此事件。
Event: 'quit'
返回:
🌐 Returns:
event活动exitCode整数
当应用退出时发出。
🌐 Emitted when the application is quitting.
在 Windows 上,如果应用因系统关机/重启或用户注销而关闭,则不会触发此事件。
Event: 'open-file' macOS
返回:
🌐 Returns:
event活动path字符串
当用户想要使用应用打开文件时会触发该事件。open-file 事件通常在应用已打开且操作系统希望重用该应用来打开文件时触发。当文件被拖到 Dock 上且应用尚未运行时,也会触发 open-file。确保在应用启动的非常早期就监听 open-file 事件以处理这种情况(甚至在 ready 事件触发之前)。
🌐 Emitted when the user wants to open a file with the application. The open-file
event is usually emitted when the application is already open and the OS wants
to reuse the application to open the file. open-file is also emitted when a
file is dropped onto the dock and the application is not yet running. Make sure
to listen for the open-file event very early in your application startup to
handle this case (even before the ready event is emitted).
如果你想处理这个事件,你应该调用 event.preventDefault()。
🌐 You should call event.preventDefault() if you want to handle this event.
在 Windows 上,你必须解析 process.argv(在主进程中)来获取文件路径。
🌐 On Windows, you have to parse process.argv (in the main process) to get the
filepath.
Event: 'open-url' macOS
返回:
🌐 Returns:
event活动url字符串
当用户想要使用应用打开 URL 时会触发此事件。你的应用的 Info.plist 文件必须在 CFBundleURLTypes 键中定义 URL 方案,并将 NSPrincipalClass 设置为 AtomApplication。
🌐 Emitted when the user wants to open a URL with the application. Your application's
Info.plist file must define the URL scheme within the CFBundleURLTypes key, and
set NSPrincipalClass to AtomApplication.
与 open-file 事件一样,请确保在应用启动早期为 open-url 事件注册监听器,以检测应用是否因处理某个 URL 而被打开。如果你在响应 ready 事件时注册监听器,就会遗漏触发应用启动的 URL。
🌐 As with the open-file event, be sure to register a listener for the open-url
event early in your application startup to detect if the application is being opened to handle a URL.
If you register the listener in response to a ready event, you'll miss URLs that trigger the launch of your application.
Event: 'activate' macOS
返回:
🌐 Returns:
event活动hasVisibleWindows布尔值
当应用被激活时触发。多种操作都可能触发此事件,例如首次启动应用、尝试在应用已运行的情况下重新启动它,或点击应用的停靠栏或任务栏图标。
🌐 Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon.
Event: 'did-become-active' macOS
返回:
🌐 Returns:
event活动
当应用变为活跃状态时触发。与 activate 事件不同的是,did-become-active 会在每次应用变为活跃状态时触发,而不仅仅是在点击 Dock 图标或重新启动应用时触发。用户通过 macOS 应用切换器切换到该应用时也会触发该事件。
🌐 Emitted when the application becomes active. This differs from the activate event in
that did-become-active is emitted every time the app becomes active, not only
when Dock icon is clicked or application is re-launched. It is also emitted when a user
switches to the app via the macOS App Switcher.
Event: 'did-resign-active' macOS
返回:
🌐 Returns:
event活动
当应用不再活跃且没有焦点时触发。例如,可以通过点击其他应用或使用 macOS 应用切换器切换到其他应用来触发此事件。
🌐 Emitted when the app is no longer active and doesn’t have focus. This can be triggered, for example, by clicking on another application or by using the macOS App Switcher to switch to another application.
Event: 'continue-activity' macOS
返回:
🌐 Returns:
event活动type字符串 - 用于标识活动的字符串。对应NSUserActivity.activityType。userInfo未知 - 包含由另一设备上的活动存储的应用特定状态。details对象webpageURL字符串(可选)- 用于标识由其他设备上的活动访问的网页 URL 的字符串(如果可用)。
当来自其他设备的活动想要恢复时,在 交接 期间会发出此事件。如果你想处理此事件,应调用 event.preventDefault()。
🌐 Emitted during Handoff when an activity from a different device wants
to be resumed. You should call event.preventDefault() if you want to handle
this event.
用户活动只能在与活动的源应用具有相同开发者团队ID且支持该活动类型的应用中继续。支持的活动类型在应用的 Info.plist 中通过 NSUserActivityTypes 键指定。
🌐 A user activity can be continued only in an app that has the same developer Team
ID as the activity's source app and that supports the activity's type.
Supported activity types are specified in the app's Info.plist under the
NSUserActivityTypes key.
Event: 'will-continue-activity' macOS
返回:
🌐 Returns:
event活动type字符串 - 用于标识活动的字符串。对应NSUserActivity.activityType。
在 交接 期间发出,当来自不同设备的活动想要恢复时。 如果你想处理此事件,你应该调用 event.preventDefault()。
🌐 Emitted during Handoff before an activity from a different device wants
to be resumed. You should call event.preventDefault() if you want to handle
this event.
Event: 'continue-activity-error' macOS
返回:
🌐 Returns:
event活动type字符串 - 用于标识活动的字符串。对应NSUserActivity.activityType。error字符串 - 包含错误本地化描述的字符串。
在 交接 期间发出,当来自不同设备的活动无法恢复时。
🌐 Emitted during Handoff when an activity from a different device fails to be resumed.
Event: 'activity-was-continued' macOS
返回:
🌐 Returns:
event活动type字符串 - 用于标识活动的字符串。对应NSUserActivity.activityType。userInfo未知 - 包含由该活动存储的应用特定状态。
在 交接 期间发出,当此设备上的某项活动在另一台设备上成功恢复时。
🌐 Emitted during Handoff after an activity from this device was successfully resumed on another one.
Event: 'update-activity-state' macOS
返回:
🌐 Returns:
event活动type字符串 - 用于标识活动的字符串。对应NSUserActivity.activityType。userInfo未知 - 包含由该活动存储的应用特定状态。
当 交接 即将在另一台设备上恢复时触发。如果你需要更新要传输的状态,应立即调用 event.preventDefault(),构建一个新的 userInfo 字典,并及时调用 app.updateCurrentActivity()。否则,操作将失败,并且会调用 continue-activity-error。
🌐 Emitted when Handoff is about to be resumed on another device. If you need to update the state to be transferred, you should call event.preventDefault() immediately, construct a new userInfo dictionary and call app.updateCurrentActivity() in a timely manner. Otherwise, the operation will fail and continue-activity-error will be called.
Event: 'new-window-for-tab' macOS
返回:
🌐 Returns:
event活动
当用户点击原生 macOS 新建标签按钮时会触发该事件。只有当前的 BrowserWindow 具有 tabbingIdentifier 时,才会显示新建标签按钮。
🌐 Emitted when the user clicks the native macOS new tab button. The new
tab button is only visible if the current BrowserWindow has a
tabbingIdentifier.
你必须在此处理程序中创建一个窗口,以便 macOS 的标签页功能按预期工作。
🌐 You must create a window in this handler in order for macOS tabbing to work as expected.
Event: 'browser-window-blur'
返回:
🌐 Returns:
event活动window浏览器窗口
当 browserWindow 失去焦点时触发。
🌐 Emitted when a browserWindow gets blurred.
Event: 'browser-window-focus'
返回:
🌐 Returns:
event活动window浏览器窗口
当 browserWindow 获得焦点时触发。
🌐 Emitted when a browserWindow gets focused.
Event: 'browser-window-created'
返回:
🌐 Returns:
event活动window浏览器窗口
当创建新的 browserWindow 时触发。
🌐 Emitted when a new browserWindow is created.
Event: 'web-contents-created'
返回:
🌐 Returns:
event活动webContents网页内容
当创建新的 webContents 时触发。
🌐 Emitted when a new webContents is created.
Event: 'certificate-error'
返回:
🌐 Returns:
event活动webContents网页内容url字符串error字符串 - 错误代码certificate证书callback函数isTrusted布尔值 - 是否将证书视为受信任
isMainFrame布尔值
在验证 url 的 certificate 失败时触发,要信任该证书,你应使用 event.preventDefault() 阻止默认行为并调用 callback(true)。
🌐 Emitted when failed to verify the certificate for url, to trust the
certificate you should prevent the default behavior with
event.preventDefault() and call callback(true).
const { app } = require('electron')
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') {
// Verification logic.
event.preventDefault()
callback(true)
} else {
callback(false)
}
})
Event: 'select-client-certificate'
返回:
🌐 Returns:
请求客户端证书时发出。
🌐 Emitted when a client certificate is requested.
url 对应于请求客户端证书的导航条目,而 callback 可以使用从列表中筛选出的条目进行调用。使用 event.preventDefault() 可防止应用使用存储中的第一个证书。
🌐 The url corresponds to the navigation entry requesting the client certificate
and callback can be called with an entry filtered from the list. Using
event.preventDefault() prevents the application from using the first
certificate from the store.
const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})
Event: 'login'
返回:
🌐 Returns:
event活动webContents网页内容(可选)authenticationResponseDetails对象url网址pid号码
authInfo对象isProxy布尔值scheme字符串host字符串port整数realm字符串
callback函数username字符串(可选)password字符串(可选)
当 webContents 或 实用程序进程 想要进行基本身份验证时触发。
🌐 Emitted when webContents or Utility process wants to do basic auth.
默认行为是取消所有身份验证。要覆盖此行为,你应使用 event.preventDefault() 阻止默认行为,并使用凭据调用 callback(username, password)。
🌐 The default behavior is to cancel all authentications. To override this you
should prevent the default behavior with event.preventDefault() and call
callback(username, password) with the credentials.
const { app } = require('electron')
app.on('login', (event, webContents, details, authInfo, callback) => {
event.preventDefault()
callback('username', 'secret')
})
如果调用 callback 时没有提供用户名或密码,身份验证请求将被取消,并且身份验证错误将返回到页面。
🌐 If callback is called without a username or password, the authentication
request will be cancelled and the authentication error will be returned to the
page.
Event: 'gpu-info-update'
每当 GPU 信息更新时发出。
🌐 Emitted whenever there is a GPU info update.
Event: 'render-process-gone'
返回:
🌐 Returns:
event活动webContents网页内容detailsRenderProcessGoneDetails
当渲染进程意外消失时触发。这通常是由于进程崩溃或被终止。
🌐 Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
Event: 'child-process-gone'
返回:
🌐 Returns:
event活动details对象type字符串 - 处理类型。可取以下值之一:UtilityZygoteSandbox helperGPUPepper PluginPepper Plugin BrokerUnknown
reason字符串 - 子进程消失的原因。可能的取值:clean-exit- 进程退出,退出代码为零abnormal-exit- 进程以非零退出代码退出killed- 进程被发送 SIGTERM 或以其他方式从外部终止crashed- 进程崩溃oom- 进程内存不足launch-failed- 进程从未成功启动integrity-failure- Windows 代码完整性检查失败memory-eviction- 主动终止进程以防止将来出现内存不足 (OOM) 的情况。
exitCode编号 - 进程的退出代码(例如,在 POSIX 上来自 waitpid 的状态,在 Windows 上来自 GetExitCodeProcess)。serviceName字符串(可选)- 进程的非本地化名称。name字符串(可选)- 进程的名称。 实用示例:Audio Service、Content Decryption Module Service、Network Service、Video Capture等。
当子进程意外消失时触发。通常这是因为它崩溃或被终止。它不包括渲染进程。
🌐 Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes.
Event: 'accessibility-support-changed' macOS Windows
返回:
🌐 Returns:
event活动accessibilitySupportEnabled布尔值 - 当 Chrome 的辅助功能支持启用时为true,否则为false。
当 Chrome 的无障碍支持发生变化时触发。当辅助技术(例如屏幕阅读器)被启用或禁用时,会触发此事件。有关更多详细信息,请参阅 https://www.chromium.org/developers/design-documents/accessibility。
🌐 Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.
Event: 'session-created'
返回:
🌐 Returns:
session会议
当 Electron 创建了一个新的 session 时触发。
🌐 Emitted when Electron has created a new session.
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
Event: 'second-instance'
返回:
🌐 Returns:
event活动argvstring[] - 第二个实例的命令行参数数组workingDirectory字符串 - 第二个实例的工作目录additionalData未知 - 来自第二个实例传递的附加数据的 JSON 对象
当第二个实例被执行并调用 app.requestSingleInstanceLock() 时,此事件将在应用的主实例中触发。
🌐 This event will be emitted inside the primary instance of your application
when a second instance has been executed and calls app.requestSingleInstanceLock().
argv 是第二个实例的命令行参数数组,workingDirectory 是它当前的工作目录。通常,应用会通过使其主窗口获得焦点并非最小化来响应这一点。
argv 不会与传递给第二个实例的参数完全相同。顺序可能会改变,并且可能会附加额外的参数。
如果需要保持完全相同的参数,建议使用 additionalData。
如果第二个实例是由不同于第一个实例的用户启动的,argv 数组将不包含参数。
该事件保证会在 app 的 ready 事件被触发后触发。
🌐 This event is guaranteed to be emitted after the ready event of app
gets emitted.
额外的命令行参数可能会被 Chromium 添加,
例如 --original-process-start-time。
方法
🌐 Methods
app 对象具有以下方法:
🌐 The app object has the following methods:
一些方法仅在特定操作系统上可用,并且会被标注为此。
app.quit()
尝试关闭所有窗口。首先会触发 before-quit 事件。如果所有窗口成功关闭,将会触发 will-quit 事件,默认情况下应用将会终止。
🌐 Try to close all windows. The before-quit event will be emitted first. If all
windows are successfully closed, the will-quit event will be emitted and by
default the application will terminate.
此方法保证所有 beforeunload 和 unload 事件处理程序都能正确执行。窗口有可能通过在 beforeunload 事件处理程序中返回 false 来取消退出。
🌐 This method guarantees that all beforeunload and unload event handlers are
correctly executed. It is possible that a window cancels the quitting by
returning false in the beforeunload event handler.
app.exit([exitCode])
exitCode整数(可选)
立即以 exitCode 退出。exitCode 默认为 0。
🌐 Exits immediately with exitCode. exitCode defaults to 0.
所有窗口将立即关闭,而不会询问用户,并且 before-quit 和 will-quit 事件将不会触发。
🌐 All windows will be closed immediately without asking the user, and the before-quit
and will-quit events will not be emitted.
app.relaunch([options])
当前实例退出时重新启动应用。
🌐 Relaunches the app when the current instance exits.
默认情况下,新的实例将使用与当前实例相同的工作目录和命令行参数。当指定 args 时,args 将作为命令行参数传递。当指定 execPath 时,将执行 execPath 以重新启动,而不是当前应用。
🌐 By default, the new instance will use the same working directory and command line
arguments as the current instance. When args is specified, the args will be
passed as the command line arguments instead. When execPath is specified, the
execPath will be executed for the relaunch instead of the current app.
请注意,此方法在执行时不会退出应用。在调用 app.relaunch 后,你必须调用 app.quit 或 app.exit 才能使应用重新启动。
🌐 Note that this method does not quit the app when executed. You have to call
app.quit or app.exit after calling app.relaunch to make the app restart.
当app.relaunch被多次调用时,每次当前实例退出后都会启动新的实例。
🌐 When app.relaunch is called multiple times, multiple instances will be
started after the current instance exits.
立即重新启动当前实例并向新实例添加新的命令行参数的示例:
🌐 An example of restarting the current instance immediately and adding a new command line argument to the new instance:
const { app } = require('electron')
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0)
app.isReady()
如果 Electron 已经完成初始化,则返回 boolean - true,否则返回 false。
另请参见 app.whenReady()。
🌐 Returns boolean - true if Electron has finished initializing, false otherwise.
See also app.whenReady().
app.whenReady()
返回 Promise<void> - 当 Electron 初始化完成时会被满足。如果应用尚未准备好,可以用它作为检查 app.isReady() 并订阅 ready 事件的便捷替代方法。
🌐 Returns Promise<void> - fulfilled when Electron is initialized.
May be used as a convenient alternative to checking app.isReady()
and subscribing to the ready event if the app is not ready yet.
app.focus([options])
在 Linux 上,聚焦第一个可见窗口。在 macOS 上,使应用成为活动应用。在 Windows 上,聚焦应用的第一个窗口。
🌐 On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window.
你应该尽可能少使用 steal 选项。
🌐 You should seek to use the steal option as sparingly as possible.
app.hide() macOS
隐藏所有应用窗口而不最小化它们。
🌐 Hides all application windows without minimizing them.
app.isHidden() macOS
如果应用——包括它的所有窗口——被隐藏(例如使用 Command-H),则返回 boolean - true,否则返回 false。
🌐 Returns boolean - true if the application—including all of its windows—is hidden (e.g. with Command-H), false otherwise.
app.show() macOS
显示被隐藏的应用窗口。不会自动将其置于前端。
🌐 Shows application windows after they were hidden. Does not automatically focus them.
app.setAppLogsPath([path])
path字符串(可选)- 自定义日志路径。必须为绝对路径。
设置或创建一个用于存放应用日志的目录,然后可以使用 app.getPath() 或 app.setPath(pathName, newPath) 对其进行操作。
🌐 Sets or creates a directory your app's logs which can then be manipulated with app.getPath() or app.setPath(pathName, newPath).
在不传递 path 参数的情况下调用 app.setAppLogsPath(),将在 macOS 上将该目录设置为 ~/Library/Logs/YourAppName,在 Linux 和 Windows 上则设置在 userData 目录中。
🌐 Calling app.setAppLogsPath() without a path parameter will result in this directory being set to ~/Library/Logs/YourAppName on macOS, and inside the userData directory on Linux and Windows.
app.getAppPath()
返回 string - 当前应用目录。
🌐 Returns string - The current application directory.
app.getPath(name)
name字符串 - 你可以通过名称请求以下路径:home用户的主目录。appData每用户应用数据目录,默认指向:%APPDATA%在 Windows 上- 在 Linux 上的
$XDG_CONFIG_HOME或~/.config ~/Library/Application Support在 macOS 上
assets存放应用资源(如resources.pak)的目录。默认情况下,这与包含exe路径的文件夹相同。仅在 Windows 和 Linux 上可用。userData用于存放应用配置文件的目录,默认情况下是appData目录后加上你的应用名称。按照惯例,存储用户数据的文件应写入此目录,并且不建议在此处写入大型文件,因为某些环境可能会将此目录备份到云存储。sessionData用于存储Session生成的数据的目录,例如 localStorage、cookies、磁盘缓存、已下载的词典、网络状态、DevTools 文件。默认情况下,此目录指向userData。Chromium 可能会在这里写入非常大的磁盘缓存,因此如果你的应用不依赖浏览器存储(如 localStorage 或 cookies)来保存用户数据,建议将此目录设置到其他位置,以避免污染userData目录。temp临时目录。exe当前的可执行文件。moduleChromium 模块的位置。默认情况下,这与exe相同。desktop当前用户的桌面目录。documents目录用于存放用户的“我的文档”。downloads用户下载目录。music用户音乐的目录。pictures用户图片的目录。videos用户视频的目录。recent目录用于存放用户的最近文件(仅限 Windows)。logs目录用于存放你应用的日志文件夹。crashDumps存储崩溃转储的目录。
返回 string - 与 name 关联的特殊目录或文件的路径。失败时,会抛出 Error。
🌐 Returns string - A path to a special directory or file associated with name. On
failure, an Error is thrown.
如果在未先调用 app.setAppLogsPath() 的情况下调用 app.getPath('logs'),将会创建一个默认的日志目录,相当于调用 app.setAppLogsPath() 时未提供 path 参数。
🌐 If app.getPath('logs') is called without calling app.setAppLogsPath() being called first, a default log directory will be created equivalent to calling app.setAppLogsPath() without a path parameter.
app.getFileIcon(path[, options])
path字符串
返回 Promise<NativeImage> - 包含应用的图标,这是一个 NativeImage。
🌐 Returns Promise<NativeImage> - fulfilled with the app's icon, which is a NativeImage.
获取路径的关联图标。
🌐 Fetches a path's associated icon.
在 Windows 上,有两种图标:
🌐 On Windows, there are 2 kinds of icons:
- 与某些文件扩展名相关的图标,例如
.mp3、.png等。 - 文件内部的图标,例如
.exe、.dll、.ico。
在 Linux 和 macOS 上,图标取决于与文件 MIME 类型关联的应用。
🌐 On Linux and macOS, icons depend on the application associated with file mime type.
app.setPath(name, path)
name字符串path字符串
将 path 覆盖到与 name 关联的特殊目录或文件。如果路径指定的目录不存在,则会抛出 Error。在这种情况下,应使用 fs.mkdirSync 或类似方法创建该目录。
🌐 Overrides the path to a special directory or file associated with name.
If the path specifies a directory that does not exist, an Error is thrown.
In that case, the directory should be created with fs.mkdirSync or similar.
你只能覆盖在 app.getPath 中定义的 name 的路径。
🌐 You can only override paths of a name defined in app.getPath.
默认情况下,网页的 cookies 和缓存将存储在 sessionData 目录下。如果你想更改此位置,必须在 app 模块发出 ready 事件之前重写 sessionData 路径。
🌐 By default, web pages' cookies and caches will be stored under the sessionData
directory. If you want to change this location, you have to override the
sessionData path before the ready event of the app module is emitted.
app.getVersion()
返回 string - 已加载应用的版本。如果在应用的 package.json 文件中未找到版本,将返回当前打包包或可执行文件的版本。
🌐 Returns string - The version of the loaded application. If no version is found in the
application's package.json file, the version of the current bundle or
executable is returned.
app.getName()
返回 string - 当前应用的名称,即应用 package.json 文件中的名称。
🌐 Returns string - The current application's name, which is the name in the application's
package.json file.
通常,package.json 的 name 字段是一个小写的短名称,根据 npm 模块规范。你通常还应该指定一个 productName 字段,这是你的应用完整的首字母大写名称,并且在 Electron 中会优先于 name。
🌐 Usually the name field of package.json is a short lowercase name, according
to the npm modules spec. You should usually also specify a productName
field, which is your application's full capitalized name, and which will be
preferred over name by Electron.
app.setName(name)
name字符串
覆盖当前应用的名称。
🌐 Overrides the current application's name.
该函数会覆盖 Electron 内部使用的名称;它不会影响操作系统使用的名称。
app.getLocale()
返回 string - 当前应用的语言环境,通过 Chromium 的 l10n_util 库获取。可能的返回值已在此处记录。
🌐 Returns string - The current application locale, fetched using Chromium's l10n_util library.
Possible return values are documented here.
要设置区域,你可以在应用启动时使用命令行开关,该开关可以在这里找到。
🌐 To set the locale, you'll want to use a command line switch at app startup, which may be found here.
在分发你的打包应用时,你还必须随附 locales 文件夹。
这个 API 必须在 ready 事件触发后调用。
要查看此 API 相对于其他地区和语言 API 的示例返回值,请参见 app.getPreferredSystemLanguages()。
app.getLocaleCountryCode()
返回 string - 用户操作系统的本地化两位字母 ISO 3166 国家代码。该值来自本地操作系统 API。
🌐 Returns string - User operating system's locale two-letter ISO 3166 country code. The value is taken from native OS APIs.
当无法检测到本地国家代码时,它会返回空字符串。
app.getSystemLocale()
返回 string - 当前系统区域设置。在 Windows 和 Linux 上,使用 Chromium 的 i18n 库获取。在 macOS 上,则使用 [NSLocale currentLocale]。要获取用户当前的系统语言(这不总是与区域设置相同),最好使用 app.getPreferredSystemLanguages()。
🌐 Returns string - The current system locale. On Windows and Linux, it is fetched using Chromium's i18n library. On macOS, [NSLocale currentLocale] is used instead. To get the user's current system language, which is not always the same as the locale, it is better to use app.getPreferredSystemLanguages().
不同的操作系统对区域数据的使用也不同:
🌐 Different operating systems also use the regional data differently:
- Windows 11 使用数字、日期和时间的区域格式。
- macOS Monterey 使用该区域来格式化数字、日期、时间以及选择要使用的货币符号。
因此,此 API 可用于选择日历应用中渲染日期和时间的格式等目的,特别是当开发者希望格式与操作系统一致时。
🌐 Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS.
这个 API 必须在 ready 事件触发后调用。
要查看此 API 相对于其他地区和语言 API 的示例返回值,请参见 app.getPreferredSystemLanguages()。
app.getPreferredSystemLanguages()
返回 string[] - 用户偏好的系统语言,从最偏好到最不偏好,包括适用的国家代码。用户可以在 Windows 或 macOS 上通过“语言与地区”设置修改和添加此列表。
🌐 Returns string[] - The user's preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings.
该 API 在 Windows 上使用 GlobalizationPreferences(如不可用则回退到 GetSystemPreferredUILanguages)、在 macOS 上使用 \[NSLocale preferredLanguages\]、在 Linux 上使用 g_get_language_names。
🌐 The API uses GlobalizationPreferences (with a fallback to GetSystemPreferredUILanguages) on Windows, \[NSLocale preferredLanguages\] on macOS, and g_get_language_names on Linux.
此 API 可用于确定应用以何种语言渲染等目的。
🌐 This API can be used for purposes such as deciding what language to present the application in.
以下是具有不同配置的各种语言和区域设置 API 的返回值的一些示例:
🌐 Here are some examples of return values of the various language and locale APIs with different configurations:
在 Windows 上,给定的应用区域设置为德语,区域格式为芬兰语(芬兰),首选系统语言从最首选到最不首选为法语(加拿大)、英语(美国)、简体中文(中国)、芬兰语和西班牙语( 拉美):
🌐 On Windows, given application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America):
app.getLocale() // 'de'
app.getSystemLocale() // 'fi-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']
在 macOS 上,鉴于应用区域设置为德语,区域为芬兰,首选系统语言从最首选到最不首选为法语(加拿大)、英语(美国)、简体中文和西班牙语(拉丁美洲):
🌐 On macOS, given the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America):
app.getLocale() // 'de'
app.getSystemLocale() // 'fr-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']
两个操作系统之间的可用语言和区域以及可能的返回值都不同。
🌐 Both the available languages and regions and the possible return values differ between the two operating systems.
从上面的例子可以看出,在 Windows 上,首选系统语言可能没有国家代码,并且首选系统语言之一可能与用于区域格式的语言相对应。在 macOS 上,区域更多地充当默认国家代码:用户不需要将芬兰语设为首选语言即可将地区设置为芬兰,而且对于语言名称中没有关联国家的首选系统语言,会使用国家代码 FI 作为国家代码。
🌐 As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn't need to have Finnish as a preferred language to use Finland as the region, and the country code FI is used as the country code for preferred system languages that do not have associated countries in the language name.
app.addRecentDocument(path) macOS Windows
path字符串
将 path 添加到最近文档列表中。
🌐 Adds path to the recent documents list.
此列表由操作系统管理。在 Windows 上,你可以从任务栏访问该列表,在 macOS 上,你可以从 Dock 菜单访问它。
🌐 This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu.
app.clearRecentDocuments() macOS Windows
清除最近的文档列表。
🌐 Clears the recent documents list.
app.getRecentDocuments() macOS Windows
返回 string[] - 一个包含最近文档列表中文档的数组。
🌐 Returns string[] - An array containing documents in the most recent documents list.
const { app } = require('electron')
const path = require('node:path')
const file = path.join(app.getPath('desktop'), 'foo.txt')
app.addRecentDocument(file)
const recents = app.getRecentDocuments()
console.log(recents) // ['/path/to/desktop/foo.txt'}
app.setAsDefaultProtocolClient(protocol[, path, args])
protocol字符串 - 你的协议名称,不包括://。例如,如果你希望你的应用处理electron://链接,请使用electron作为参数调用此方法。path字符串(可选)Windows - Electron 可执行文件的路径。默认值为process.execPathargsstring[](可选)Windows - 传递给可执行文件的参数。默认值为空数组
返回 boolean - 调用是否成功。
🌐 Returns boolean - Whether the call succeeded.
将当前可执行文件设置为某个协议(也称为 URI 方案)的默认处理程序。它允许你将应用更深地集成到操作系统中。一旦注册,所有带有 your-protocol:// 的链接都将使用当前可执行文件打开。整个链接,包括协议部分,将作为参数传递给你的应用。
🌐 Sets the current executable as the default handler for a protocol (aka URI
scheme). It allows you to integrate your app deeper into the operating system.
Once registered, all links with your-protocol:// will be opened with the
current executable. The whole link, including protocol, will be passed to your
application as a parameter.
在 macOS 上,你只能注册已添加到你的应用 info.plist 的协议,而该文件在运行时无法修改。不过,你可以在构建时通过 Electron Forge、Electron 打包工具 或使用文本编辑器编辑 info.plist 来更改该文件。详情请参阅 苹果的文档。
在 Windows 应用商店环境中(当打包为 appx 时),此 API 对所有调用都会返回 true,但它设置的注册表项无法被其他应用访问。为了将你的 Windows 应用商店应用注册为默认协议处理程序,你必须在清单中声明该协议。
该 API 内部使用 Windows 注册表和 LSSetDefaultHandlerForURLScheme。
🌐 The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
app.removeAsDefaultProtocolClient(protocol[, path, args]) macOS Windows
protocol字符串 - 你的协议名称,不包含://。path字符串(可选)Windows - 默认值为process.execPathargs字符串数组(可选)Windows - 默认为空数组
返回 boolean - 调用是否成功。
🌐 Returns boolean - Whether the call succeeded.
此方法检查当前可执行文件是否为某个协议(即 URI 方案)的默认处理程序。如果是,它将移除该应用作为默认处理程序。
🌐 This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler.
app.isDefaultProtocolClient(protocol[, path, args])
protocol字符串 - 你的协议名称,不包含://。path字符串(可选)Windows - 默认值为process.execPathargs字符串数组(可选)Windows - 默认为空数组
返回 boolean - 当前可执行文件是否是某个协议(亦称 URI 方案)的默认处理程序。
🌐 Returns boolean - Whether the current executable is the default handler for a
protocol (aka URI scheme).
在 macOS 上,你可以使用此方法来检查应用是否已被注册为某个协议的默认处理程序。你也可以通过在 macOS 机器上检查 ~/Library/Preferences/com.apple.LaunchServices.plist 来验证这一点。详情请参阅 苹果的文档。
该 API 内部使用 Windows 注册表和 LSCopyDefaultHandlerForURLScheme。
🌐 The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
app.getApplicationNameForProtocol(url)
url字符串 - 要检查的带有协议名称的 URL。与该系列中的其他方法不同,它接受整个 URL,至少包括://(例如https://)。
返回 string——处理该协议的应用名称,如果没有处理程序,则返回空字符串。例如,如果 Electron 是该 URL 的默认处理程序,在 Windows 和 Mac 上这可能是 Electron。但是,不要依赖其精确格式,因为格式不保证保持不变。在 Linux 上可能会有不同的格式,可能带有 .desktop 后缀。
🌐 Returns string - Name of the application handling the protocol, or an empty
string if there is no handler. For instance, if Electron is the default
handler of the URL, this could be Electron on Windows and Mac. However,
don't rely on the precise format which is not guaranteed to remain unchanged.
Expect a different format on Linux, possibly with a .desktop suffix.
此方法返回 URL 协议(也称 URI 方案)默认处理程序的应用名称。
🌐 This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL.
app.getApplicationInfoForProtocol(url) macOS Windows
url字符串 - 要检查的带有协议名称的 URL。与该系列中的其他方法不同,它接受整个 URL,至少包括://(例如https://)。
返回 Promise<Object> - 解析为包含以下内容的对象:
🌐 Returns Promise<Object> - Resolve with an object containing the following:
iconNativeImage - 处理该协议的应用的显示图标。path字符串 - 处理该协议的应用的安装路径。name字符串 - 处理该协议的应用的显示名称。
此方法返回一个包含 URL 协议(即 URI 方案)的默认处理程序的应用名称、图标和路径的 Promise。
🌐 This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL.
app.setUserTasks(tasks) Windows
tasks任务[] -Task对象的数组
将 tasks 添加到 Windows 上跳转列表的 任务 类别中。
🌐 Adds tasks to the Tasks category of the Jump List on Windows.
tasks 是一个 Task 对象的数组。
返回 boolean - 调用是否成功。
🌐 Returns boolean - Whether the call succeeded.
如果你想进一步自定义跳转列表,可以使用 app.setJumpList(categories)。
app.getJumpListSettings() Windows
返回 Object:
🌐 Returns Object:
minItems整数 - 在跳转列表中将显示的最少项目数量(有关此值的更详细描述,请参阅 MSDN 文档)。removedItemsJumpListItem[] - 包含JumpListItem对象的数组,这些对象对应用户已从 Jump List 的自定义分类中明确移除的项目。在下一次调用app.setJumpList()时,不能将这些项目重新添加到 Jump List 中,Windows 不会显示包含任何已移除项目的自定义分类。
app.setJumpList(categories) Windows
categoriesJumpListCategory[] |null-JumpListCategory对象的数组。
返回 string
🌐 Returns string
为应用设置或删除自定义跳转列表,并返回以下字符串之一:
🌐 Sets or removes a custom Jump List for the application, and returns one of the following strings:
ok- 没有出什么问题。error- 发生了一个或多个错误,请启用运行时日志以找出可能的原因。invalidSeparatorError- 尝试在跳转列表的自定义类别中添加分隔符。分隔符仅允许在标准的Tasks类别中使用。fileTypeRegistrationError- 尝试将文件链接添加到该应用未注册处理的文件类型的跳转列表中。customCategoryAccessDeniedError- 由于用户隐私或组策略设置,无法将自定义类别添加到跳转列表。
如果 categories 是 null,之前设置的自定义跳转列表(如果有)将被该应用的标准跳转列表(由 Windows 管理)取代。
🌐 If categories is null the previously set custom Jump List (if any) will be
replaced by the standard Jump List for the app (managed by Windows).
如果一个 JumpListCategory 对象既没有设置 type 也没有设置 name 属性,则其 type 被假定为 tasks。如果设置了 name 属性但省略了 type 属性,则 type 被假定为 custom。
用户可以从自定义类别中移除项目,Windows 不会允许已移除的项目重新添加到自定义类别中,直到下次成功调用 app.setJumpList(categories) 之后。在此之前尝试将已移除的项目重新添加到自定义类别中,将导致整个自定义类别在跳转列表中被省略。可以使用 app.getJumpListSettings() 获取已移除项目的列表。
跳转列表项的 description 属性的最大长度为 260 个字符。超过此限制,该项将不会被添加到跳转列表,也不会显示。
这是创建自定义跳转列表的一个非常简单的示例:
🌐 Here's a very simple example of creating a custom Jump List:
const { app } = require('electron')
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so `type` is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}
]
},
{ type: 'frequent' },
{ // has no name and no type so `type` is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{ type: 'separator' },
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}
]
}
])
app.requestSingleInstanceLock([additionalData])
- 'additionalData' 记录<any, any> (可选)——包含额外数据的 JSON 对象,用于发送给第一个实例。
返回 boolean
🌐 Returns boolean
此方法的返回值表示你的应用实例是否成功获得锁。如果未能获得锁,你可以假设已有另一个应用实例正在持有锁并立即退出。
🌐 The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately.
即。如果你的进程是应用的主实例,并且应用应继续加载,则此方法返回 true。如果你的进程应立即退出,因为它已将参数发送给已经获取锁的另一个实例,则返回 false。
🌐 I.e. This method returns true if your process is the primary instance of your
application and your app should continue loading. It returns false if your
process should immediately quit as it has sent its parameters to another
instance that has already acquired the lock.
在 macOS 上,当用户尝试在 Finder 中打开你的应用的第二个实例时,系统会自动强制单实例,并且会触发 open-file 和 open-url 事件。然而,当用户在命令行启动你的应用时,系统的单实例机制将被绕过,你需要使用此方法来保证单实例。
🌐 On macOS, the system enforces single instance automatically when users try to open
a second instance of your app in Finder, and the open-file and open-url
events will be emitted for that. However when users start your app in command
line, the system's single instance mechanism will be bypassed, and you have to
use this method to ensure single instance.
当第二个实例启动时,激活主实例窗口的示例:
🌐 An example of activating the window of primary instance when a second instance starts:
const { app, BrowserWindow } = require('electron')
let myWindow = null
const additionalData = { myKey: 'myValue' }
const gotTheLock = app.requestSingleInstanceLock(additionalData)
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => {
// Print out data received from the second instance.
console.log(additionalData)
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
app.whenReady().then(() => {
myWindow = new BrowserWindow({})
myWindow.loadURL('https://electron.nodejs.cn')
})
}
app.hasSingleInstanceLock()
返回 boolean
🌐 Returns boolean
此方法返回你的应用实例当前是否持有单实例锁。你可以使用 app.requestSingleInstanceLock() 请求锁,并使用 app.releaseSingleInstanceLock() 释放锁。
🌐 This method returns whether or not this instance of your app is currently
holding the single instance lock. You can request the lock with
app.requestSingleInstanceLock() and release with
app.releaseSingleInstanceLock()
app.releaseSingleInstanceLock()
释放所有由 requestSingleInstanceLock 创建的锁。这将允许应用的多个实例再次并行运行。
🌐 Releases all locks that were created by requestSingleInstanceLock. This will
allow multiple instances of the application to once again run side by side.
app.setUserActivity(type, userInfo[, webpageURL]) macOS
type字符串 - 唯一标识该活动。映射到NSUserActivity.activityType。userInfo任意 - 用于由另一台设备使用的应用特定状态存储。webpageURL字符串(可选)- 如果在恢复设备上没有安装合适的应用,将在浏览器中加载的网页。该方案必须是http或https。
创建一个 NSUserActivity 并将其设置为当前活动。该活动随后有资格被 交接 到另一个设备。
🌐 Creates an NSUserActivity and sets it as the current activity. The activity
is eligible for Handoff to another device afterward.
app.getCurrentActivityType() macOS
返回 string - 当前正在运行的活动的类型。
🌐 Returns string - The type of the currently running activity.
app.invalidateCurrentActivity() macOS
使当前的 交接 用户活动失效。
🌐 Invalidates the current Handoff user activity.
app.resignCurrentActivity() macOS
将当前 交接 用户活动标记为不活跃,但不使其失效。
🌐 Marks the current Handoff user activity as inactive without invalidating it.
app.updateCurrentActivity(type, userInfo) macOS
type字符串 - 唯一标识该活动。映射到NSUserActivity.activityType。userInfo任意 - 用于由另一台设备使用的应用特定状态存储。
如果当前活动的类型与 type 匹配,则更新该活动,将 userInfo 中的条目合并到其当前的 userInfo 字典中。
🌐 Updates the current activity if its type matches type, merging the entries from
userInfo into its current userInfo dictionary.
app.setAppUserModelId(id) Windows
id字符串
将 应用用户模型ID 更改为 id。
🌐 Changes the Application User Model ID to id.
app.setToastActivatorCLSID(id) Windows
id字符串
将 Toast 激活器 CLSID 更改为 id。如果没有通过此方法设置,则会为应用随机生成一个。
🌐 Changes the Toast Activator CLSID to id. If one is not set via this method, it will be randomly generated for the app.
- 该值必须是以下形式之一的有效 GUID/CLSID:
- 规范大括号封装:
{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}(首选) - 无大括号的规范形式:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(大括号将自动添加)
- 规范大括号封装:
- 十六进制数字不区分大小写。
此方法应尽早调用(在显示通知之前),以便该值被嵌入到注册/快捷方式中。提供空字符串或不可解析的值会抛出异常,并保持现有(或生成的)CLSID不变。如果从未调用此方法,每次运行时都会生成一个随机 CLSID,并通过 app.toastActivatorCLSID 进行暴露。
🌐 This method should be called early (before showing notifications) so the value is baked into the registration/shortcut. Supplying an empty string or an unparsable value throws and leaves the existing (or generated) CLSID unchanged. If this method is never called, a random CLSID is generated once per run and exposed via app.toastActivatorCLSID.
app.setActivationPolicy(policy) macOS
policy字符串 - 可以是 'regular'、'accessory' 或 'prohibited'。
设置给定应用的激活策略。
🌐 Sets the activation policy for a given app.
激活策略类型:
🌐 Activation policy types:
- “常规” - 该应用是一个普通应用,会出现在 Dock 中,并可能有用户界面。
- “配件” - 该应用不会出现在 Dock 中,也没有菜单栏,但可以通过编程方式或点击其某个窗口来激活。
- “禁止” - 该应用不会出现在 Dock 中,也可能无法创建窗口或被激活。
app.importCertificate(options, callback) Linux
callback函数result整数 - 导入的结果。
将 pkcs12 格式的证书导入到平台证书存储中。
callback 会在导入操作的 result 上被调用,值为 0 表示成功,而其他任何值表示失败,具体参见 Chromium net_error_list。
🌐 Imports the certificate in pkcs12 format into the platform certificate store.
callback is called with the result of import operation, a value of 0
indicates success while any other value indicates failure according to Chromium net_error_list.
app.configureHostResolver(options)
配置主机解析(DNS 和 DNS-over-HTTPS)。默认情况下,将按以下顺序使用以下解析器:
🌐 Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order:
- DNS-over-HTTPS,如果是 DNS 提供商支持它,那么
- 内置解析器(默认情况下仅在 macOS 上启用),然后
- 系统的解析器(例如
getaddrinfo)。
这可以配置为限制使用未加密的 DNS(secureDnsMode: "secure"),或禁用 DNS-over-HTTPS(secureDnsMode: "off")。也可以启用或禁用内置解析器。
🌐 This can be configured to either restrict usage of non-encrypted DNS
(secureDnsMode: "secure"), or disable DNS-over-HTTPS (secureDnsMode: "off"). It is also possible to enable or disable the built-in resolver.
要禁用不安全的 DNS,你可以将 secureDnsMode 设置为 "secure"。如果这样做,你应该确保提供一个可用的 DNS-over-HTTPS 服务器列表,以防用户的 DNS 配置中不包含支持 DoH 的提供商。
🌐 To disable insecure DNS, you can specify a secureDnsMode of "secure". If you do
so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in
case the user's DNS configuration does not include a provider that supports
DoH.
const { app } = require('electron')
app.whenReady().then(() => {
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: [
'https://cloudflare-dns.com/dns-query'
]
})
})
这个 API 必须在触发 ready 事件之后调用。
🌐 This API must be called after the ready event is emitted.
app.disableHardwareAcceleration()
禁用当前应用的硬件加速。
🌐 Disables hardware acceleration for current app.
此方法只能在应用准备就绪之前调用。
🌐 This method can only be called before app is ready.
app.isHardwareAccelerationEnabled()
返回 boolean - 当前硬件加速是否已启用。
🌐 Returns boolean - whether hardware acceleration is currently enabled.
[!注意] 此信息仅在
gpu-info-update事件触发后可用。
app.disableDomainBlockingFor3DAPIs()
默认情况下,如果 GPU 进程频繁崩溃,Chromium 会在每个域的基础上禁用 3D API(例如 WebGL),直到重启为止。此功能会禁用该行为。
🌐 By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU process crashes too frequently. This function disables that behavior.
此方法只能在应用准备就绪之前调用。
🌐 This method can only be called before app is ready.
app.getAppMetrics()
返回 ProcessMetric[]:一个 ProcessMetric 对象数组,对应与应用关联的所有进程的内存和 CPU 使用情况统计。
🌐 Returns ProcessMetric[]: Array of ProcessMetric objects that correspond to memory and CPU usage statistics of all the processes associated with the app.
app.getGPUFeatureStatus()
返回 GPUFeatureStatus - 来自 chrome://gpu/ 的图形功能状态。
🌐 Returns GPUFeatureStatus - The Graphics Feature Status from chrome://gpu/.
只有在触发 gpu-info-update 事件后,这些信息才可使用。
app.getGPUInfo(infoType)
infoType字符串 - 可以是basic或complete。
返回 Promise<unknown>
🌐 Returns Promise<unknown>
当 infoType 等于 complete 时:
Promise 会被履行,Object 包含所有 GPU 信息,格式与 chromium 的 GPUInfo 对象 相同。这包括在 chrome://gpu 页面上显示的版本和驱动程序信息。
🌐 For infoType equal to complete:
Promise is fulfilled with Object containing all the GPU Information as in chromium's GPUInfo object. This includes the version and driver information that's shown on chrome://gpu page.
当 infoType 等于 basic 时:
Promise 会被履行,返回的 Object 包含的属性比使用 complete 请求时少。以下是基本响应的示例:
🌐 For infoType equal to basic:
Promise is fulfilled with Object containing fewer attributes than when requested with complete. Here's an example of basic response:
{
auxAttributes:
{
amdSwitchable: true,
canSupportThreadedTextureMailbox: false,
directComposition: false,
directRendering: true,
glResetNotificationStrategy: 0,
inProcessGpu: true,
initializationTime: 0,
jpegDecodeAcceleratorSupported: false,
optimus: false,
passthroughCmdDecoder: false,
sandboxed: false,
softwareRendering: false,
supportsOverlays: false,
videoDecodeAcceleratorFlags: 0
},
gpuDevice:
[{ active: true, deviceId: 26657, vendorId: 4098 },
{ active: false, deviceId: 3366, vendorId: 32902 }],
machineModelName: 'MacBookPro',
machineModelVersion: '11.5'
}
如果只需要像 vendorId 或 deviceId 这样的基本信息,应该优先使用 basic。
🌐 Using basic should be preferred if only basic information like vendorId or deviceId is needed.
如果 GPU 被完全禁用,即没有可用的硬件和软件实现,Promise 将被拒绝。
🌐 Promise is rejected if the GPU is completely disabled, i.e. no hardware and software implementations are available.
app.setBadgeCount([count]) Linux macOS
count整数(可选)- 如果提供了值,则将徽章设置为提供的值;否则,在 macOS 上显示一个普通的白点(例如,未知数量的通知)。在 Linux 上,如果未提供值,徽章将不显示。
返回 boolean - 调用是否成功。
🌐 Returns boolean - Whether the call succeeded.
设置当前应用的计数徽章。将计数设置为 0 将隐藏徽章。
🌐 Sets the counter badge for current app. Setting the count to 0 will hide the
badge.
在 macOS 上,它会显示在 Dock 图标上。在 Linux 上,它只适用于 Unity 启动器。
🌐 On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.
Unity 启动器需要一个 .desktop 文件才能运行。更多信息,
请阅读 Unity 集成文档。
在 macOS 上,你需要确保你的应用具有显示通知的权限,才能使此方法生效。
app.getBadgeCount() Linux macOS
返回 Integer - 当前计数徽章显示的值。
🌐 Returns Integer - The current value displayed in the counter badge.
app.isUnityRunning() Linux
返回 boolean - 当前桌面环境是否为 Unity 启动器。
🌐 Returns boolean - Whether the current desktop environment is Unity launcher.
app.getLoginItemSettings([options]) macOS Windows
如果你向 app.setLoginItemSettings 提供了 path 和 args 选项,那么你需要在这里传递相同的参数,以便正确设置 openAtLogin。
🌐 If you provided path and args options to app.setLoginItemSettings, then you
need to pass the same arguments here for openAtLogin to be set correctly.
返回 Object:
🌐 Returns Object:
openAtLogin布尔值 -true如果应用设置为开机自启。openAsHidden布尔值 macOS 已弃用 -true如果应用设置为登录时以隐藏方式打开。此功能在 macOS 13 及更高版本中无效。wasOpenedAtLogin布尔值 macOS -true表示应用是否在登录时自动打开。wasOpenedAsHidden布尔值 macOS 已弃用 -true如果应用作为隐藏的登录项打开。这表示应用在启动时不应打开任何窗口。此设置在 MAS 构建 或 macOS 13 及更高版本中不可用。restoreState布尔值 macOS 已弃用 -true如果应用作为登录项打开,则应从上一个会话恢复状态。这表示应用应恢复上次关闭应用时打开的窗口。此设置在 MAS 构建 或 macOS 13 及更高版本上不可用。status字符串_macOS_ - 可以是not-registered、enabled、requires-approval或not-found中的一个。executableWillLaunchAtLogin布尔值 Windows -true如果应用设置为开机启动且其运行键未被禁用。这与openAtLogin不同,因为它忽略了args选项,如果给定的可执行文件将在登录时以任何参数启动,则此属性为真。launchItems对象[] Windowsname字符串 Windows - 注册表项的名称值。path字符串 Windows - 与注册表项对应的应用可执行文件。argsstring[] Windows - 传递给可执行文件的命令行参数。scope字符串 Windows -user或machine之一。表示注册表项位于HKEY_CURRENT USER还是HKEY_LOCAL_MACHINE下。enabled布尔值 Windows -true如果应用注册表键被批准为启动,因此在任务管理器和 Windows 设置中显示为enabled。
app.setLoginItemSettings(settings) macOS Windows
settings对象openAtLogin布尔值(可选) -true表示在登录时打开应用,false表示将应用从登录项中移除。默认值为false。openAsHidden布尔值(可选)macOS 已弃用 -true用于以隐藏方式打开应用。默认为false。用户可以从系统偏好设置中编辑此设置,因此在应用打开时应检查app.getLoginItemSettings().wasOpenedAsHidden以了解当前值。此设置在 MAS 构建 上或 macOS 13 及以上版本不可用。type字符串(可选)macOS - 要添加为登录项的服务类型。默认值为mainAppService。仅适用于 macOS 13 及更高版本。mainAppService- 主要应用。agentService- 启动代理的属性列表名称。属性列表名称必须对应应用Contents/Library/LaunchAgents目录中的一个属性列表。daemonService字符串(可选)macOS - 启动代理的属性列表名称。该属性列表名称必须对应于应用Contents/Library/LaunchDaemons目录中的一个属性列表。loginItemService字符串(可选)macOS - 登录项服务的属性列表名称。该属性列表名称必须对应于应用Contents/Library/LoginItems目录中的一个属性列表。
serviceName字符串(可选)macOS - 服务名称。如果type非默认值,则必填。仅在 macOS 13 及以上版本可用。path字符串(可选)Windows - 登录时要启动的可执行文件。默认值为process.execPath。argsstring[](可选) Windows - 传递给可执行文件的命令行参数。默认值为空数组。请注意将路径用引号括起来。enabled布尔值(可选)Windows -true将更改启动批准的注册表键,enable / disable在任务管理器和 Windows 设置中显示应用。默认值为true。name字符串(可选)Windows - 要写入注册表的值名称。默认为应用的 AppUserModelId()。
设置应用的登录项设置。
🌐 Set the app's login item settings.
要在 Windows 上使用 Electron 的 autoUpdater(使用 Squirrel),你需要将启动路径设置为你的可执行文件名的上一级目录,该目录是由 Squirrel 自动生成的存根应用,它会自动启动最新版本。
🌐 To work with Electron's autoUpdater on Windows, which uses Squirrel,
you'll want to set the launch path to your executable's name but a directory up, which is
a stub application automatically generated by Squirrel which will automatically launch the
latest version.
const { app } = require('electron')
const path = require('node:path')
const appFolder = path.dirname(process.execPath)
const ourExeName = path.basename(process.execPath)
const stubLauncher = path.resolve(appFolder, '..', ourExeName)
app.setLoginItemSettings({
openAtLogin: true,
path: stubLauncher,
args: [
// You might want to pass a parameter here indicating that this
// app was launched via login, but you don't have to
]
})
有关在 macOS 13 及以上版本中将不同服务设置为登录项的更多信息,请参见 SMAppService。
🌐 For more information about setting different services as login items on macOS 13 and up, see SMAppService.
app.isAccessibilitySupportEnabled() macOS Windows
如果启用了 Chrome 的辅助功能支持,则返回 boolean - true,否则返回 false。如果检测到使用辅助技术(例如屏幕阅读器),此 API 将返回 true。详情请参见 https://www.chromium.org/developers/design-documents/accessibility。
🌐 Returns boolean - true if Chrome's accessibility support is enabled,
false otherwise. This API will return true if the use of assistive
technologies, such as screen readers, has been detected. See
https://www.chromium.org/developers/design-documents/accessibility for more
details.
app.setAccessibilitySupportEnabled(enabled) macOS Windows
enabled布尔值 - 启用或禁用辅助功能树渲染
手动启用 Chrome 的无障碍支持,允许在应用设置中向用户显示无障碍开关。有关更多详细信息,请参见 Chromium 的无障碍文档。默认情况下禁用。
🌐 Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See Chromium's accessibility docs for more details. Disabled by default.
这个 API 必须在触发 ready 事件之后调用。
🌐 This API must be called after the ready event is emitted.
渲染辅助功能树可能会显著影响你应用的性能。它不应默认启用。调用此方法将启用以下辅助功能支持特性:nativeAPIs、webContents、inlineTextBoxes 和 extendedProperties。
app.getAccessibilitySupportFeatures() macOS Windows
返回 string[] - 当前启用的辅助功能支持组件名称的字符串数组。可能的值有:
🌐 Returns string[] - Array of strings naming currently enabled accessibility support components. Possible values:
nativeAPIs- 已启用原生操作系统辅助功能 API 集成。webContents- 已启用 Web 内容可访问性树公开。inlineTextBoxes- 已启用内联文本框(字符边界框)。extendedProperties- 已启用扩展辅助功能属性。screenReader- 已启用屏幕阅读器特定模式。html- 已启用 HTML 可访问性树构建。labelImages- 已启用自动图片注释的辅助功能支持。pdfPrinting- 已启用 PDF 打印的辅助功能支持。
注意:
🌐 Notes:
- 如果没有启用任何辅助功能模式,则该数组可能为空。
- 使用
app.isAccessibilitySupportEnabled()进行传统布尔检查;对于细粒度诊断或遥测,更推荐使用此方法。
示例:
🌐 Example:
const { app } = require('electron')
app.whenReady().then(() => {
if (app.getAccessibilitySupportFeatures().includes('screenReader')) {
// Change some app UI to better work with Screen Readers.
}
})
app.setAccessibilitySupportFeatures(features) macOS Windows
featuresstring[] - 要启用的辅助功能数组。
可能的值为:
🌐 Possible values are:
nativeAPIs- 已启用原生操作系统辅助功能 API 集成。webContents- 已启用 Web 内容可访问性树公开。inlineTextBoxes- 已启用内联文本框(字符边界框)。extendedProperties- 已启用扩展辅助功能属性。screenReader- 已启用屏幕阅读器特定模式。html- 已启用 HTML 可访问性树构建。labelImages- 已启用自动图片注释的辅助功能支持。pdfPrinting- 已启用 PDF 打印的辅助功能支持。
要禁用所有受支持的功能,请传递一个空数组 []。
🌐 To disable all supported features, pass an empty array [].
示例:
🌐 Example:
const { app } = require('electron')
app.whenReady().then(() => {
// Enable a subset of features:
app.setAccessibilitySupportFeatures([
'screenReader',
'pdfPrinting',
'webContents'
])
// Other logic
// Some time later, disable all features:
app.setAccessibilitySupportFeatures([])
})
app.showAboutPanel()
显示应用的关于面板选项。可以使用 app.setAboutPanelOptions(options) 覆盖这些选项。此功能异步运行。
🌐 Show the app's about panel options. These options can be overridden with app.setAboutPanelOptions(options). This function runs asynchronously.
app.setAboutPanelOptions(options)
设置关于面板选项。这将覆盖 macOS 上应用 .plist 文件中定义的值。有关更多详细信息,请参阅 苹果文档。在 Linux 上,必须设置值才能显示;没有默认值。
🌐 Set the about panel options. This will override the values defined in the app's .plist file on macOS. See the Apple docs for more details. On Linux, values must be set in order to be shown; there are no defaults.
如果你没有设置 credits,但仍希望在你的应用中显示它们,AppKit 将按照顺序在 NSBundle 类方法 main 返回的包中查找名为 "Credits.html"、"Credits.rtf" 和 "Credits.rtfd" 的文件。找到的第一个文件将被使用,如果都未找到,则信息区域保持为空。有关更多信息,请参阅 Apple 文档。
🌐 If you do not set credits but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple documentation for more information.
app.isEmojiPanelSupported()
返回 boolean - 当前操作系统版本是否支持原生表情符号选择器。
🌐 Returns boolean - whether or not the current OS version allows for native emoji pickers.
app.showEmojiPanel() macOS Windows
显示平台的原生表情符号选择器。
🌐 Show the platform's native emoji picker.
app.startAccessingSecurityScopedResource(bookmarkData) MAS
bookmarkData字符串 - 由dialog.showOpenDialog或dialog.showSaveDialog方法返回的 Base64 编码的安全范围书签数据。
返回 Function - 一旦你完成对安全范围文件的访问,必须调用此函数。如果你忘记停止访问书签,内核资源将被泄漏,并且你的应用将完全失去访问沙箱外部的能力,直到应用重新启动。
🌐 Returns Function - This function must be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, kernel resources will be leaked and your app will lose its ability to reach outside the sandbox completely, until your app is restarted.
const { app, dialog } = require('electron')
const fs = require('node:fs')
let filepath
let bookmark
dialog.showOpenDialog(null, { securityScopedBookmarks: true }).then(({ filePaths, bookmarks }) => {
filepath = filePaths[0]
bookmark = bookmarks[0]
fs.readFileSync(filepath)
})
// ... restart app ...
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(bookmark)
fs.readFileSync(filepath)
stopAccessingSecurityScopedResource()
开始访问安全范围资源。使用此方法,打包用于 Mac App Store 的 Electron 应用可以突破沙箱,访问用户选择的文件。有关该系统工作原理的说明,请参阅 Apple 的文档。
🌐 Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See Apple's documentation for a description of how this system works.
app.enableSandbox()
在应用上启用完整的沙箱模式。这意味着所有渲染器都会以沙箱模式启动,而不管 WebPreferences 中的 sandbox 标志值如何。
🌐 Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the sandbox flag in WebPreferences.
此方法只能在应用准备就绪之前调用。
🌐 This method can only be called before app is ready.
app.isInApplicationsFolder() macOS
返回 boolean - 应用当前是否从系统的应用文件夹运行。与 app.moveToApplicationsFolder() 配合使用
🌐 Returns boolean - Whether the application is currently running from the
systems Application folder. Use in combination with app.moveToApplicationsFolder()
app.moveToApplicationsFolder([options]) macOS
返回 boolean - 表示移动是否成功。请注意,如果移动成功,你的应用将退出并重新启动。
🌐 Returns boolean - Whether the move was successful. Please note that if
the move is successful, your application will quit and relaunch.
默认情况下不会显示确认对话框。如果你希望允许用户确认操作,可以使用 dialog API 来实现。
🌐 No confirmation dialog will be presented by default. If you wish to allow
the user to confirm the operation, you may do so using the
dialog API.
注意: 如果移动失败的原因不是用户本身,该方法会抛出错误。例如,如果用户取消了授权对话框,该方法会返回 false。如果我们无法执行复制操作,则此方法会抛出错误。错误信息应具有指导性,明确告诉你到底出了什么问题。
默认情况下,如果在应用目录中存在与正在移动的应用同名的应用且该应用未运行,现有应用将被移至废纸篓,正在活动的应用将移动到原位置。如果该应用正在运行,则已有的运行应用将获得焦点,之前的活动应用将自行退出。通过提供可选的冲突处理器,可以更改此行为,处理器返回的布尔值决定是否使用默认行为解决移动冲突。即返回 false 将确保不采取进一步操作,返回 true 将执行默认行为并继续方法。
🌐 By default, if an app of the same name as the one being moved exists in the Applications directory and is not running, the existing app will be trashed and the active app moved into its place. If it is running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning false will ensure no further action is taken, returning true will result in the default behavior and the method continuing.
例如:
🌐 For example:
const { app, dialog } = require('electron')
app.moveToApplicationsFolder({
conflictHandler: (conflictType) => {
if (conflictType === 'exists') {
return dialog.showMessageBoxSync({
type: 'question',
buttons: ['Halt Move', 'Continue Move'],
defaultId: 0,
message: 'An app of this name already exists'
}) === 1
}
}
})
这意味着,如果用户目录中已经存在某个应用,用户选择“继续移动”时,该功能将继续其默认行为,现有的应用将被删除,活动应用将被移动到原来的位置。
🌐 Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place.
app.isSecureKeyboardEntryEnabled() macOS
返回 boolean - 表示 Secure Keyboard Entry 是否已启用。
🌐 Returns boolean - whether Secure Keyboard Entry is enabled.
默认情况下,该 API 将返回 false。
🌐 By default this API will return false.
app.setSecureKeyboardEntryEnabled(enabled) macOS
enabled布尔值 - 启用或禁用Secure Keyboard Entry
在你的应用中启用 Secure Keyboard Entry。
🌐 Set the Secure Keyboard Entry is enabled in your application.
通过使用该 API,可以防止密码等重要信息被其他进程拦截。
🌐 By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.
有关更多详细信息,请参阅 Apple 的文档。
🌐 See Apple's documentation for more details.
仅在需要时启用 Secure Keyboard Entry,不再需要时将其禁用。
app.setProxy(config)
config代理配置
返回 Promise<void> - 当代理设置进程完成时解析。
🌐 Returns Promise<void> - Resolves when the proxy setting process is complete.
设置在没有关联 Session 的情况下进行的网络请求的代理设置。目前,这将影响在 实用进程 中使用 Net 发出的请求以及运行时发出的内部请求(例如:地理位置查询)。
🌐 Sets the proxy settings for networks requests made without an associated Session. Currently this will affect requests made with Net in the utility process and internal requests made by the runtime (ex: geolocation queries).
该方法只能在应用准备好后调用。
🌐 This method can only be called after app is ready.
app.resolveProxy(url)
url网址
返回 Promise<string> - 解析为 url 的代理信息,当尝试在 utility process 中使用 Net 发起请求时将会使用该信息。
🌐 Returns Promise<string> - Resolves with the proxy information for url that will be used when attempting to make requests using Net in the utility process.
app.setClientCertRequestPasswordHandler(handler) Linux
-
handlerFunction<Promise<string>>clientCertRequestParams对象hostname字符串 - 需要客户端证书的网站主机名tokenName字符串 - 加密设备的令牌(或插槽)名称isRetry布尔值 - 是否之前有过尝试输入密码失败的情况
返回
Promise<string>- 解析密码
当需要密码来解锁 hostname 的客户端证书时,将调用该处理程序。
🌐 The handler is called when a password is needed to unlock a client certificate for
hostname.
const { app } = require('electron')
async function passwordPromptUI (text) {
return new Promise((resolve, reject) => {
// display UI to prompt user for password
// ...
// ...
resolve('the password')
})
}
app.setClientCertRequestPasswordHandler(async ({ hostname, tokenName, isRetry }) => {
const text = `Please sign in to ${tokenName} to authenticate to ${hostname} with your certificate`
const password = await passwordPromptUI(text)
return password
})
属性
🌐 Properties
app.accessibilitySupportEnabled macOS Windows
一个 boolean 属性,如果启用了 Chrome 的辅助功能支持,则为 true,否则为 false。如果检测到使用屏幕阅读器等辅助技术,该属性将为 true。手动将此属性设置为 true 可以启用 Chrome 的辅助功能支持,允许开发者在应用设置中向用户暴露辅助功能开关。
🌐 A boolean property that's true if Chrome's accessibility support is enabled, false otherwise. This property will be true if the use of assistive technologies, such as screen readers, has been detected. Setting this property to true manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings.
有关详细信息,请参阅 Chromium 的辅助功能文档。默认情况下已禁用。
🌐 See Chromium's accessibility docs for more details. Disabled by default.
这个 API 必须在触发 ready 事件之后调用。
🌐 This API must be called after the ready event is emitted.
渲染无障碍树可能会显著影响应用的性能。默认情况下不应启用。
app.applicationMenu
Menu | null 属性,如果已设置则返回 Menu,否则返回 null。用户可以传入一个 菜单 来设置此属性。
🌐 A Menu | null property that returns Menu if one has been set and null otherwise.
Users can pass a Menu to set this property.
app.badgeCount Linux macOS
Integer 属性返回当前应用的徽章计数。将计数设置为 0 将隐藏徽章。
🌐 An Integer property that returns the badge count for current app. Setting the count to 0 will hide the badge.
在 macOS 上,设置为任何非零整数都会显示在 Dock 图标上。在 Linux 上,此属性仅适用于 Unity 启动器。
🌐 On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher.
Unity 启动器需要一个 .desktop 文件才能运行。更多信息,
请阅读 Unity 集成文档。
在 macOS 上,你需要确保你的应用具有显示通知的权限,才能使此属性生效。
app.commandLine 只读
🌐 app.commandLine Readonly
一个CommandLine对象,允许你读取和操作Chromium使用的命令行参数。
🌐 A CommandLine object that allows you to read and manipulate the
command line arguments that Chromium uses.
app.dock macOS 只读
🌐 app.dock macOS Readonly
Dock | undefined 属性(在 macOS 上为 Dock,在其他所有平台上为 undefined),允许你对用户 Dock 中的应用图标执行操作。
🌐 A Dock | undefined property (Dock on macOS, undefined on all other
platforms) that allows you to perform actions on your app icon in the user's dock.
app.isPackaged 只读
🌐 app.isPackaged Readonly
boolean 属性,如果应用已打包则返回 true,否则返回 false。对于许多应用来说,该属性可以用来区分开发环境和生产环境。
🌐 A boolean property that returns true if the app is packaged, false otherwise. For many apps, this property can be used to distinguish development and production environments.
app.toastActivatorCLSID Windows 只读
🌐 app.toastActivatorCLSID Windows Readonly
一个返回应用 Toast 激活器 CLSID 的 string 属性。
🌐 A string property that returns the app's Toast Activator CLSID.
app.name
string 属性,表示当前应用的名称,即应用 package.json 文件中的名称。
🌐 A string property that indicates the current application's name, which is the name in the application's package.json file.
通常,package.json 的 name 字段是一个小写的短名称,根据 npm 模块规范。你通常还应该指定一个 productName 字段,这是你的应用完整的首字母大写名称,并且在 Electron 中会优先于 name。
🌐 Usually the name field of package.json is a short lowercase name, according
to the npm modules spec. You should usually also specify a productName
field, which is your application's full capitalized name, and which will be
preferred over name by Electron.
app.userAgentFallback
一个 string,它是 Electron 作为全局备用使用的用户代理字符串。
🌐 A string which is the user agent string Electron will use as a global fallback.
这是在 webContents 或 session 级别未设置用户代理时使用的用户代理。它对于确保整个应用使用相同的用户代理非常有用。请在应用初始化的尽早阶段设置为自定义值,以确保使用你覆盖的值。
🌐 This is the user agent that will be used when no user agent is set at the
webContents or session level. It is useful for ensuring that your entire
app has the same user agent. Set to a custom value as early as possible
in your app's initialization to ensure that your overridden value is used.
app.runningUnderARM64Translation 只读 macOS Windows
🌐 app.runningUnderARM64Translation Readonly macOS Windows
boolean 当 true 时表示该应用目前正在 ARM64 转译器下运行(例如 macOS 的 [Rosetta 转译环境](https://en.wikipedia.org/wiki/Rosetta_(software) 或 Windows 的 WOW)。
🌐 A boolean which when true indicates that the app is currently running under
an ARM64 translator (like the macOS
Rosetta Translator Environment
or Windows WOW).
你可以使用此属性来提示用户在他们错误地在 Rosetta 或 WOW 下运行 x64 版本时下载应用的 arm64 版本。
🌐 You can use this property to prompt users to download the arm64 version of your application when they are mistakenly running the x64 version under Rosetta or WOW.