app
Control your application's event lifecycle.控制应用程序的事件生命周期。
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事件
The app
object emits the following events:app
对象发出以下事件:
Event: 'will-finish-launching'
Emitted when the application has finished basic startup. 当应用程序完成基本启动时发出。On Windows and Linux, the 在Windows和Linux上,will-finish-launching
event is the same as the ready
event; on macOS, this event represents the applicationWillFinishLaunching
notification of NSApplication
. will-finish-launching
事件与ready
事件相同;在macOS上,此事件表示NSApplication
的applicationWillFinishLaunching
通知。You would usually set up listeners for the 通常在这里为open-file
and open-url
events here, and start the crash reporter and auto updater.open-file
和open-url
事件设置侦听器,并启动崩溃报告器和自动更新器。
In most cases, you should do everything in the 在大多数情况下,您应该在ready
event handler.ready
事件处理程序中执行所有操作。
Event: 'ready'
Returns:返回:
event
EventlaunchInfo
Record<string, any> | NotificationResponse macOS
Emitted once, when Electron has finished initializing. 当Electron完成初始化时,发射一次。On macOS, 在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. launchInfo
保存NSUserNotification的userInfo
或用于打开应用程序的UNNotificationResponse的信息(如果应用程序是从通知中心启动的)。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.apps.Ready()
来检查此事件是否已触发,并调用app.whenReady()
来获得在Electron初始化时实现的Promise。
Event: 'window-all-closed'
Emitted when all windows have been 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,或者开发人员调用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.app.quit()
,Electron将首先尝试关闭所有窗口,然后发出will-quit
事件,在这种情况下,不会发出window-all-closed
事件。
Event: 'before-quit'
Returns:返回:
event
Event
Emitted before the application starts closing its windows. 在应用程序开始关闭其窗口之前发出。Calling 调用event.preventDefault()
will prevent the default behavior, which is terminating the application.event.preventDefault()
将阻止终止应用程序的默认行为。
Note: If application quit was initiated by 如果应用程序退出是由autoUpdater.quitAndInstall()
, then before-quit
is emitted after emitting close
event on all windows and closing them.autoUpdater.quitAndInstall()
启动的,则在所有窗口上发出close
事件并关闭它们后,将发出before-quit
。
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.在Windows上,如果应用程序因系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
Event: 'will-quit'
Returns:返回:
event
Event
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.event.preventDefault()
将阻止终止应用程序的默认行为。
See the description of the 有关window-all-closed
event for the differences between the will-quit
and window-all-closed
events.will-quit
和window-all-closed
事件之间的差异,请参阅window-all-closed
的事件的描述。
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.在Windows上,如果应用程序因系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
Event: 'quit'
Returns:返回:
event
EventexitCode
Integer
Emitted when the application is quitting.当应用程序退出时发出。
Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.在Windows上,如果应用程序因系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
Event: 'open-file' macOS
Returns:返回:
event
Eventpath
string
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
事件通常在应用程序已经打开并且OS希望重用应用程序以打开文件时发出。open-file
is also emitted when a file is dropped onto the dock and the application is not yet running. 当文件放置到dock上且应用程序尚未运行时,也会发出。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).open-file
事件以处理这种情况(甚至在发出ready
事件之前)。
You should call 如果要处理此事件,应调用event.preventDefault()
if you want to handle this event.event.preventDefault()
。
On Windows, you have to parse 在Windows上,必须解析process.argv
(in the main process) to get the filepath.process.argv
(在主进程中)以获取文件路径。
Event: 'open-url' macOS
Returns:返回:
event
Eventurl
string
Emitted when the user wants to open a URL with the application. 当用户希望使用应用程序打开URL时发出。Your application's 应用程序的Info.plist
file must define the URL scheme within the CFBundleURLTypes
key, and set NSPrincipalClass
to AtomApplication
.Info.plist
文件必须在CFBundleURLTypes
键中定义URL方案,并将NSPrincipalClass
设置为AtomApplication
。
You should call 如果要处理此事件,应调用event.preventDefault()
if you want to handle this event.event.preventDefault()
。
Event: 'activate' macOS
Returns:返回:
event
EventhasVisibleWindows
boolean
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
Event
Emitted when mac application become active. 当mac应用程序激活时发出。Difference from 与activate
event is that did-become-active
is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched.activate
事件不同的是,每次应用程序激活时都会发出did-become-active
事件,而不仅仅是在单击Dock图标或重新启动应用程序时。
Event: 'continue-activity' macOS
Returns:返回:
event
Eventtype
string - A string identifying the activity.string - 标识活动的字符串。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。userInfo
unknown - Contains app-specific state stored by the activity on another device.unknown - 包含其他设备上活动存储的应用程序特定状态。details
ObjectwebpageURL
string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available.string(可选)- 一个字符串,标识活动在另一个设备上访问的网页的URL(如果可用)。
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.event.preventDefault()
。
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. 用户活动只能在与活动的源应用程序具有相同开发团队ID且支持活动类型的应用程序中继续。Supported activity types are specified in the app's 支持的活动类型在应用程序的Info.plist
under the NSUserActivityTypes
key.Info.plist
中的NSUserActivityTypes
键下指定。
Event: 'will-continue-activity' macOS
Returns:返回:
event
Eventtype
string - A string identifying the activity.string - 标识活动的字符串。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。
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.preventDefault()
。
Event: 'continue-activity-error' 事件:“继续活动错误”macOS
Returns:返回:
event
Eventtype
string - A string identifying the activity.string - 标识活动的字符串。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。error
string - A string with the error's localized description.string - 包含错误本地化描述的字符串。
Emitted during Handoff when an activity from a different device fails to be resumed.当无法恢复来自其他设备的活动时,在切换期间发出。
Event: 'activity-was-continued' macOS
Returns:返回:
event
Eventtype
string - A string identifying the activity.string - 标识活动的字符串。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。userInfo
unknown - Contains app-specific state stored by the activity.unknown - 包含活动存储的应用程序特定状态。
Emitted during Handoff after an activity from this device was successfully resumed on another one.此设备的活动在另一设备上成功恢复后,在切换期间发出。
Event: 'update-activity-state' macOS
Returns:返回:
event
Eventtype
string - A string identifying the activity.string - 标识活动的字符串。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。userInfo
unknown - Contains app-specific state stored by the activity.unknown - 包含活动存储的应用程序特定状态。
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. event.preventDefault()
,构造一个新的userInfo
字典,并及时调用app.updateCurrentActivity()
。Otherwise, the operation will fail and 否则,操作将失败,将调用continue-activity-error
will be called.continue-activity-error
。
Event: 'new-window-for-tab' 事件:'选项卡的新窗口'macOS
Returns:返回:
event
Event
Emitted when the user clicks the native macOS new tab button. 当用户单击本地macOS新选项卡按钮时发出。The new tab button is only visible if the current 仅当当前BrowserWindow
has a tabbingIdentifier
BrowserWindow
具有tabingIdentifier
时,新选项卡按钮才可见
Event: 'browser-window-blur'
Returns:返回:
event
Eventwindow
BrowserWindow
Emitted when a browserWindow gets blurred.当browserWindow失去焦点时发出。
Event: 'browser-window-focus'
Returns:返回:
event
Eventwindow
BrowserWindow
Emitted when a browserWindow gets focused.当browserWindow得到焦点时发出。
Event: 'browser-window-created'
Returns:返回:
event
Eventwindow
BrowserWindow
Emitted when a new browserWindow is created.创建新browserWindow时发出。
Event: 'web-contents-created'
Returns:返回:
event
EventwebContents
WebContents
Emitted when a new webContents is created.创建新的webContents时发出。
Event: 'certificate-error'
Returns:返回:
event
EventwebContents
WebContentsurl
stringerror
string -The error code错误代码certificate
Certificatecallback
FunctionisTrusted
boolean - Whether to consider the certificate as trustedboolean - 是否将证书视为可信证书
isMainFrame
boolean
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)
.url
的certificate
失败时发出,为了信任证书,应该使用event.preventDefault()
和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:返回:
event
EventwebContents
WebContentsurl
URLcertificateList
Certificate[]callback
Functioncertificate
Certificate (optional)
Emitted when a client certificate is requested.请求客户端证书时发出。
The url
corresponds to the navigation entry requesting the client certificate and callback
can be called with an entry filtered from the list. url
对应于请求客户端证书的导航条目,可以使用从列表中筛选的条目调用callback
。Using 使用event.preventDefault()
prevents the application from using the first certificate from the store.event.preventDefault()
可防止应用程序使用存储中的第一个证书。
const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})
Event: 'login'
Returns:返回:
event
EventwebContents
WebContentsauthenticationResponseDetails
Objecturl
URL
authInfo
ObjectisProxy
booleanscheme
stringhost
stringport
Integerrealm
string
callback
Functionusername
string (optional)password
string (optional)
Emitted when 当webContents
wants to do basic auth.webContents
想要进行基本身份验证时发出。
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.event.preventDefault()
阻止默认行为,并使用凭据调用callback(username, password)
。
const { app } = require('electron')
app.on('login', (event, webContents, details, authInfo, callback) => {
event.preventDefault()
callback('username', 'secret')
})
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.callback
,则将取消身份验证请求,并将身份验证错误返回到页面。
Event: 'gpu-info-update'
Emitted whenever there is a GPU info update.每当GPU信息更新时发出。
Event: 'gpu-process-crashed' Deprecated
Returns:返回:
event
Eventkilled
boolean
Emitted when the GPU process crashes or is killed.当GPU进程崩溃或被终止时发出。
Deprecated: This event is superceded by the 此事件被child-process-gone
event which contains more information about why the child process disappeared. child-process-gone
事件取代,该事件包含有关子进程消失原因的更多信息。It isn't always because it crashed. 这并不总是因为它坠毁了。The 切换到该事件时,可以通过检查killed
boolean can be replaced by checking reason === 'killed'
when you switch to that event.reason === 'killed'
来替换killed
布尔值。
Event: 'renderer-process-crashed' Deprecated
Returns:返回:
event
EventwebContents
WebContentskilled
boolean
Emitted when the renderer process of 当webContents
crashes or is killed.webContents
的渲染器进程崩溃或被终止时发出。
Deprecated: This event is superceded by the 此事件被render-process-gone
event which contains more information about why the render process disappeared. render-process-gone
事件取代,该事件包含有关渲染进程消失原因的更多信息。It isn't always because it crashed. 这并不总是因为它坠毁了。The 当您切换到该事件时,可以通过检查killed
boolean can be replaced by checking reason === 'killed'
when you switch to that event.reason === 'killed'
来替换killed
布尔值。
Event: 'render-process-gone'
Returns:返回:
event
EventwebContents
WebContentsdetails
Objectreason
string -The reason the render process is gone.渲染过程消失的原因。Possible values:可能的值:clean-exit
-Process exited with an exit code of zero进程退出,退出代码为零abnormal-exit
-Process exited with a non-zero exit code进程已退出,退出代码为非零killed
-Process was sent a SIGTERM or otherwise killed externally进程被发送SIGTERM或以其他方式从外部终止crashed
-Process crashed进程崩溃oom
-Process ran out of memory进程内存不足launch-failed
-Process never successfully launched进程从未成功启动integrity-failure
-Windows code integrity checks failedWindows代码完整性检查失败
exitCode
Integer -The exit code of the process, unless进程的退出代码,除非reason
islaunch-failed
, in which caseexitCode
will be a platform-specific launch failure error code.reason
是launch-failed
,在这种情况下,exitCode
将是特定于平台的启动失败错误代码。
Emitted when the renderer process unexpectedly disappears. 当渲染器进程意外消失时发出。This is normally because it was crashed or killed.这通常是因为它坠毁或死亡。
Event: 'child-process-gone'
Returns:返回:
event
Eventdetails
Objecttype
string -Process type.流程类型。One of the following values:以下值之一:Utility
Zygote
Sandbox helper
GPU
Pepper Plugin
Pepper Plugin Broker
Unknown
reason
string -The reason the child process is gone.子进程消失的原因。Possible values:可能的值:clean-exit
-Process exited with an exit code of zero进程退出,退出代码为零abnormal-exit
-Process exited with a non-zero exit code进程已退出,退出代码为非零killed
-Process was sent a SIGTERM or otherwise killed externally进程被发送SIGTERM或以其他方式从外部终止crashed
-Process crashed进程崩溃oom
-Process ran out of memory进程内存不足launch-failed
-Process never successfully launched进程从未成功启动integrity-failure
-Windows code integrity checks failedWindows代码完整性检查失败
exitCode
number -The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows).进程的退出代码(例如,如果在posix上,则来自waitpid的状态,或者来自Windows上的GetExitCodeProcess的状态)。serviceName
string (optional) -The non-localized name of the process.进程的非本地化名称。name
string (optional) -The name of the process.进程的名称。Examples for utility:实用程序示例:Audio Service
,Content Decryption Module Service
,Network Service
,Video Capture
, etc.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
EventaccessibilitySupportEnabled
boolean -启用Chrome的辅助功能支持时为true
when Chrome's accessibility support is enabled,false
otherwise.true
,否则为false
。
Emitted when Chrome's accessibility support changes. Chrome的辅助功能支持更改时发出。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.请参阅https://www.chromium.org/developers/design-documents/accessibility以了解更多详细信息。
Event: 'session-created'
Returns:返回:
session
Session
Emitted when Electron has created a new Electron创建新session
.session
时发射。
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
Event: 'second-instance'
Returns:返回:
event
Eventargv
string[] -An array of the second instance's command line arguments第二个实例的命令行参数的数组workingDirectory
string -The second instance's working directory第二个实例的工作目录additionalData
unknown -A JSON object of additional data passed from the second instance从第二个实例传递的附加数据的JSON对象
This event will be emitted inside the primary instance of your application when a second instance has been executed and calls 当执行第二个实例并调用app.requestSingleInstanceLock()
.appequestSingleInstanceLock()
时,此事件将在应用程序的主实例内发出。
argv
is an Array of the second instance's command line arguments, and workingDirectory
is its current working directory. argv
是第二个实例的命令行参数的数组,workingDirectory
是其当前的工作目录。Usually applications respond to this by making their primary window focused and non-minimized.通常,应用程序通过使其主窗口集中且不最小化来对此作出响应。
Note: If the second instance is started by a different user than the first, the 如果第二个实例由与第一个实例不同的用户启动,则argv
array will not include the arguments.argv
数组将不包括参数。
This event is guaranteed to be emitted after the 此事件保证在ready
event of app
gets emitted.app
的ready
事件发出后发出。
Note: Extra command line arguments might be added by Chromium, such as Chromium可能会添加额外的命令行参数,例如--original-process-start-time
.--original-process-start-time
。
Methods方法
The app
object has the following methods:app
对象具有以下方法:
Note: Some methods are only available on specific operating systems and are labeled as such.某些方法仅在特定的操作系统上可用,并被标记为这样。
app.quit()
Try to close all windows. 尝试关闭所有窗口。The 将首先发出before-quit
event will be emitted first. before-quit
事件。If all windows are successfully closed, the 如果所有窗口都成功关闭,将发出will-quit
event will be emitted and by default the application will terminate.will-quit
事件,默认情况下应用程序将终止。
This method guarantees that all 此方法可确保所有beforeunload
and unload
event handlers are correctly executed. beforeunload
和unload
事件处理程序都能正确执行。It is possible that a window cancels the quitting by returning 窗口可能通过在false
in the beforeunload
event handler.beforeunload
事件处理程序中返回false
来取消退出。
app.exit([exitCode])
exitCode
Integer (optional)
Exits immediately with 使用exitCode
. exitCode
defaults to 0.exitCode
立即退出。exitCode
默认为0。
All windows will be closed immediately without asking the user, and the 所有窗口将立即关闭,而无需询问用户,并且不会发出before-quit
and will-quit
events will not be emitted.before-quit
和will-quit
事件。
app.relaunch([options])
Relaunches the app when current instance exits.当当前实例退出时重新启动应用程序。
By default, the new instance will use the same working directory and command line arguments with current instance. 默认情况下,新实例将使用与当前实例相同的工作目录和命令行参数。When 当指定了args
is specified, the args
will be passed as command line arguments instead. args
时,这些args
将作为命令行参数传递。When 当指定execPath
is specified, the execPath
will be executed for relaunch instead of current app.execPath
时,将执行execPath
以重新启动,而不是当前应用程序。
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
后调用app.quit
或app.exit
才能重新启动应用程序。
When 当多次调用app.relaunch
is called for multiple times, multiple instances will be started after current instance exited.app.relaunch
时,当前实例退出后会启动多个实例。
An example of restarting 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()
Returns 返回boolean
- true
if Electron has finished initializing, false
otherwise. boolean
- 如果Electron已完成初始化,则返回true
,否则返回false
。See also 另请参阅app.whenReady()
.app.whenReady()
。
app.whenReady()
Returns 返回Promise<void>
- fulfilled when Electron is initialized. Electron初始化时完成。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.isReady()
和订阅ready
事件的方便替代方法。
app.focus([options])
On Linux, focuses on the first visible window. On macOS, makes the application the active app. 在Linux上,重点关注第一个可见窗口。在macOS上,使应用程序成为活动应用程序。On Windows, focuses on the application's first window.在Windows上,重点关注应用程序的第一个窗口。
You should seek to use the 你应该尽量少用steal
option as sparingly as possible.steal
选项。
app.hide()
macOS
Hides all application windows without minimizing them.隐藏所有应用程序窗口而不最小化它们。
app.isHidden()
macOS
Returns 返回boolean
- 如果应用程序包括其所有窗口都被隐藏(例如使用true
if the application—including all of its windows—is hidden (e.g. with Command-H
), false
otherwise.Command-H
),则为true
,否则为false
。
app.show()
macOS
Shows application windows after they were hidden. 显示隐藏后的应用程序窗口。Does not automatically focus them.不会自动聚焦。
app.setAppLogsPath([path])
path
string (optional) -A custom path for your logs.日志的自定义路径。Must be absolute.必须是绝对的。
Sets or creates a directory your app's logs which can then be manipulated with 设置或创建应用程序日志的目录,然后可以使用app.getPath()
or app.setPath(pathName, newPath)
.app.getPath()
或app.setPath(pathName, newPath)
对其进行操作。
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.path
参数的情况下调用app.setAppLogsPath()
将导致此目录在macOS上设置为~/Library/Logs/YourAppName
,在Linux和Windows上设置为userData
目录。
app.getAppPath()
Returns 返回string
- The current application directory.当前应用程序目录。
app.getPath(name)
name
string -You can request the following paths by the name:您可以通过名称请求以下路径:home
User's home directory.用户的主目录。appData
Per-user application data directory, which by default points to:每个用户的应用程序数据目录,默认情况下指向:Windows上的%APPDATA%
on Windows%APPDATA%
Linux上的$XDG_CONFIG_HOME
or~/.config
on Linux$XDG_CONFIG_HOME
或~/.config
MacOS上的~/Library/Application Support
on macOS~/Library/Application Support
userData
The directory for storing your app's configuration files, which by default is the用于存储应用程序配置文件的目录,默认情况下是附加了应用程序名称的appData
directory appended with your app's name.appData
目录。By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage.按照惯例,存储用户数据的文件应写入此目录,不建议在此处写入大文件,因为某些环境可能会将此目录备份到云存储。sessionData
The directory for storing data generated by用于存储Session
, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files.Session
生成的数据的目录,如localStorage、cookie、磁盘缓存、下载的词典、网络状态、devtools文件。By default this points to默认情况下,它指向userData
.userData
。Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting theChromium可能会在此处写入非常大的磁盘缓存,因此,如果您的应用程序不依赖浏览器存储(如localStorage或cookie)来保存用户数据,建议将此目录设置为其他位置,以避免污染userData
directory.userData
目录。temp
Temporary directory.临时目录。exe
The current executable file.当前可执行文件。module
Thelibchromiumcontent
library.libchromiumcontent
库。desktop
The current user's Desktop directory.当前用户的桌面目录。documents
Directory for a user's "My Documents".用户“我的文档”的目录;。downloads
Directory for a user's downloads.用户下载的目录。music
Directory for a user's music.用户音乐的目录。pictures
Directory for a user's pictures.用户图片的目录。videos
Directory for a user's videos.用户视频的目录。recent
Directory for the user's recent files (Windows only).用户最近文件的目录(仅限Windows)。logs
Directory for your app's log folder.应用程序日志文件夹的目录。crashDumps
Directory where crash dumps are stored.存储故障转储的目录。
Returns 返回string
- A path to a special directory or file associated with name
. string
- 与name
关联的特殊目录或文件的路径。On failure, an 失败时,将引发一个Error
is thrown.Error
。
If 如果调用app.getPath('logs')
is called without called app.setAppLogsPath()
being called first, a default log directory will be created equivalent to calling app.setAppLogsPath()
without a path
parameter.app.getPath('logs')
时没有首先调用被调用的app.setAppLogsPath()
,则将创建一个默认日志目录,相当于在没有path
参数的情况下调用app.setAppLogsPath()
。
app.getFileIcon(path[, options])
path
string
Returns 返回Promise<NativeImage>
- fulfilled with the app's icon, which is a NativeImage.Promise<NativeImage>
- 用应用程序的图标实现,该图标是NativeImage。
Fetches a path's associated icon.获取路径的关联图标。
On Windows, there a 2 kinds of icons:在Windows上,有两种图标:
Icons associated with certain file extensions, like与某些文件扩展名相关联的图标,如.mp3
,.png
, etc..mp3
、.png
等。Icons inside the file itself, like文件内部的图标,如.exe
,.dll
,.ico
..exe
、.dll
、.ico
。
On Linux and macOS, icons depend on the application associated with file mime type.在Linux和macOS上,图标取决于与文件mime类型相关的应用程序。
app.setPath(name, path)
name
stringpath
string
Overrides the 覆盖与path
to a special directory or file associated with name
. name
关联的特殊目录或文件的path
。If the path specifies a directory that does not exist, an 如果路径指定的目录不存在,则会引发Error
is thrown. Error
。In that case, the directory should be created with 在这种情况下,应该使用fs.mkdirSync
or similar.fs.mkdirSync
或类似方法创建目录。
You can only override paths of a 您只能覆盖在name
defined in app.getPath
.app.getPath
中定义的name
的路径。
By default, web pages' cookies and caches will be stored under the 默认情况下,网页的cookie和缓存将存储在sessionData
directory. sessionData
目录下。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
模块的ready
事件之前覆盖sessionData
路径。
app.getVersion()
Returns 返回string
- The version of the loaded application. string
- 加载的应用程序的版本。If no version is found in the application's 如果在应用程序的package.json
file, the version of the current bundle or executable is returned.package.json
文件中找不到版本,则返回当前捆绑包或可执行文件的版本。
app.getName()
Returns 返回string
- The current application's name, which is the name in the application's package.json
file.string
- 当前应用程序的名称,即应用程序的package.json
文件中的名称。
Usually the 根据npm模块规范, name
field of package.json
is a short lowercase name, according to the npm modules spec. package.json
的name
字段通常是一个小写的短名称。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.productName
字段,这是您的应用程序的大写全名,它将优先于Electron的name
。
app.setName(name)
name
string
Overrides the current application's name.覆盖当前应用程序的名称。
Note: This function overrides the name used internally by Electron; it does not affect the name that the OS uses.此函数覆盖Electron内部使用的名称;它不会影响操作系统使用的名称。
app.getLocale()
Returns 返回string
- The current application locale, fetched using Chromium's l10n_util
library. string
- 使用Chromium的l10n_util
库获取的当前应用程序区域设置。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.要设置区域设置,您需要在应用程序启动时使用命令行开关,可以在此处找到。
Note: When distributing your packaged app, you have to also ship the 分发打包的应用程序时,还必须附带locales
folder.locales
文件夹。
Note: On Windows, you have to call it after the 在Windows上,您必须在ready
events gets emitted.ready
事件发出后调用它。
app.getLocaleCountryCode()
Returns 返回string
- User operating system's locale two-letter ISO 3166 country code. string
- 用户操作系统的区域设置,由两个字母组成的ISO 3166国家代码。The value is taken from native OS APIs.该值取自本机操作系统API。
Note: When unable to detect locale country code, it returns empty string.当无法检测区域设置国家/地区代码时,它将返回空字符串。
app.addRecentDocument(path)
macOS Windows
path
string
Adds 将path
to the recent documents list.path
添加到最近的文档列表。
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.在Windows上,您可以从任务栏访问列表,在macOS上,您也可以从dock菜单访问列表。
app.clearRecentDocuments()
macOS Windows
Clears the recent documents list.清除最近的文档列表。
app.setAsDefaultProtocolClient(protocol[, path, args])
protocol
string -The name of your protocol, without您的协议名称,不带://
.://
。For example, if you want your app to handle例如,如果您希望您的应用程序处理electron://
links, call this method withelectron
as the parameter.electron://
链接,请使用electron
作为参数调用此方法。path
string (optional) Windows -The path to the Electron executable.Electron可执行文件的路径。Defaults to默认为process.execPath
args
string[] (optional) Windows -Arguments passed to the executable. Defaults to an empty array传递给可执行文件的参数。默认为空数组
Returns 返回boolean
boolean
- Whether the call succeeded.呼叫是否成功。
Sets the current executable as the default handler for a protocol (aka URI scheme). 将当前可执行文件设置为协议(又名URI方案)的默认处理程序。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. your-protocol://
的所有链接都将使用当前可执行文件打开。The whole link, including protocol, will be passed to your application as a parameter.整个链接,包括协议,将作为参数传递给您的应用程序。
Note: On macOS, you can only register protocols that have been added to your app's 在macOS上,您只能注册已添加到应用程序info.plist
, which cannot be modified at runtime. info.plist
的协议,该协议在运行时无法修改。However, you can change the file during build time via Electron Forge, Electron Packager, or by editing 但是,您可以在构建期间通过Electron Forge、Electron Packager或使用文本编辑器编辑info.plist
with a text editor. info.plist
来更改文件。Please refer to Apple's documentation for details.有关详细信息,请参阅苹果公司的文档。
Note: In a Windows Store environment (when packaged as an 在Windows应用商店环境中(打包为appx
) this API will return true
for all calls but the registry key it sets won't be accessible by other applications. appx
时),此API将为所有调用返回true
,但其他应用程序无法访问它设置的注册表项。In order to register your Windows Store application as a default protocol handler you must declare the protocol in your manifest.为了将Windows应用商店应用程序注册为默认协议处理程序,您必须在清单中声明该协议。
The API uses the Windows Registry and API在内部使用Windows注册表和LSSetDefaultHandlerForURLScheme
internally.LSSetDefaultHandlerForURLScheme
。
app.removeAsDefaultProtocolClient(protocol[, path, args])
macOS Windows
protocol
string -The name of your protocol, without您的协议名称,不带://
.://
。path
string (optional) Windows -Defaults to默认为process.execPath
args
string[] (optional) Windows -Defaults to an empty array默认为空数组
Returns 返回boolean
- Whether the call succeeded.呼叫是否成功。
This method checks if the current executable as the default handler for a protocol (aka URI scheme). 此方法检查当前可执行文件是否作为协议(又名URI方案)的默认处理程序。If so, it will remove the app as the default handler.如果是这样,它将删除该应用程序作为默认处理程序。
app.isDefaultProtocolClient(protocol[, path, args])
protocol
string -The name of your protocol, without您的协议名称,不带://
.://
。path
string (optional) Windows -Defaults to默认为process.execPath
args
string[] (optional) Windows -Defaults to an empty array默认为空数组
Returns 返回boolean
- Whether the current executable is the default handler for a protocol (aka URI scheme).当前可执行文件是否是协议(又名URI方案)的默认处理程序。
Note: On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. 在macOS上,您可以使用此方法检查应用程序是否已注册为协议的默认协议处理程序。You can also verify this by checking 您也可以通过检查macOS机器上的~/Library/Preferences/com.apple.LaunchServices.plist
on the macOS machine. ~/Library/Preferences/com.apple.LaunchServices.plist
来验证这一点。Please refer to Apple's documentation for details.有关详细信息,请参阅苹果公司的文档。
The API uses the Windows Registry and API在内部使用Windows注册表和LSCopyDefaultHandlerForURLScheme
internally.LSCopyDefaultHandlerForURLScheme
。
app.getApplicationNameForProtocol(url)
url
string -a URL with the protocol name to check.带有要检查的协议名称的URL。Unlike the other methods in this family, this accepts an entire URL, including与该系列中的其他方法不同,它接受整个URL,至少包括://
at a minimum (e.g.https://
).://
(例如https://
)。
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是URL的默认处理程序,那么它可能是Windows和Mac上的Electron
on Windows and Mac. Electron
。However, don't rely on the precise format which is not guaranteed to remain unchanged. 然而,不要依赖精确的格式,因为它不能保证保持不变。Expect a different format on Linux, possibly with a 在Linux上预期会有不同的格式,可能带有.desktop
suffix..desktop
后缀。
This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL.此方法返回URL的协议(又名URI方案)的默认处理程序的应用程序名称。
app.getApplicationInfoForProtocol(url)
macOS Windows
url
string -a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including带有要检查的协议名称的URL。与该系列中的其他方法不同,它接受整个URL,至少包括://
at a minimum (e.g.https://
).://
(例如https://
)。
Returns 返回Promise<Object>
- Resolve with an object containing the following:使用包含以下内容的对象进行解析:
icon
NativeImage -the display icon of the app handling the protocol.处理协议的应用程序的显示图标。path
string -installation path of the app handling the protocol.处理协议的应用程序的安装路径。name
string -display name of the app handling the protocol.处理协议的应用程序的显示名称。
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.此方法返回一个promise,其中包含URL的协议(又名URI方案)的默认处理程序的应用程序名称、图标和路径。
app.setUserTasks(tasks)
Windows
tasks
Task[] -Array ofTask
objectsTask
对象数组
Adds 将tasks
to the Tasks category of the Jump List on Windows.tasks
添加到Windows上“跳转列表”的Tasks类别中。
tasks
is an array of Task objects.tasks
是Task对象的数组。
Returns 返回boolean
- Whether the call succeeded.呼叫是否成功。
Note: If you'd like to customize the Jump List even more use 如果您想自定义跳转列表,请使用app.setJumpList(categories)
instead.app.setJumpList(categories)
。
app.getJumpListSettings()
Windows
Returns 返回Object
:
minItems
Integer -The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the MSDN docs).将在跳转列表中显示的最小项目数(有关此值的详细描述,请参阅MSDN文档)。removedItems
JumpListItem[] -Array ofJumpListItem
objects that correspond to items that the user has explicitly removed from custom categories in the Jump List.JumpListItem
对象的数组,这些对象对应于用户已从跳转列表中的自定义类别中明确删除的项目。These items must not be re-added to the Jump List in the next call to在下一次调用app.setJumpList()
, Windows will not display any custom category that contains any of the removed items.app.setJumpList()
时,这些项目不得重新添加到跳转列表中,Windows将不会显示任何包含任何已删除项目的自定义类别。
app.setJumpList(categories)
Windows
categories
JumpListCategory[] |null
-Array ofJumpListCategory
objects.JumpListCategory
对象的数组。
Returns 返回string
Sets or removes a custom Jump List for the application, and returns one of the following strings:设置或删除应用程序的自定义跳转列表,并返回以下字符串之一:
ok
-Nothing went wrong.没有出什么问题。error
-One or more errors occurred, enable runtime logging to figure out the likely cause.出现一个或多个错误,请启用运行时日志记录以找出可能的原因。invalidSeparatorError
-An attempt was made to add a separator to a custom category in the Jump List.试图在跳转列表中的自定义类别中添加分隔符。Separators are only allowed in the standard分隔符只允许出现在标准的Tasks
category.Tasks
类别中。fileTypeRegistrationError
-An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle.试图为应用程序未注册处理的文件类型向跳转列表添加文件链接。customCategoryAccessDeniedError
-Custom categories can't be added to the Jump List due to user privacy or group policy settings.由于用户隐私或组策略设置的原因,无法将自定义类别添加到跳转列表中。
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).categories
为null
,则之前设置的自定义跳转列表(如果有)将被应用程序的标准跳转列表(由Windows管理)所取代。
Note: If a 如果JumpListCategory
object has neither the type
nor the name
property set then its type
is assumed to be tasks
. JumpListCategory
对象既没有type
也没有name
属性集,则假定其type
为tasks
。If the 如果设置了name
property is set but the type
property is omitted then the type
is assumed to be custom
.name
属性,但省略了type
属性,则假定该type
是custom
。
Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until after the next successful call to 用户可以从自定义类别中删除项目,在下一次成功调用app.setJumpList(categories)
. app.setJumpList(categories)
之前,Windows不允许将已删除的项目添加回自定义类别。Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. 任何提前将已删除的项目重新添加到自定义类别的尝试都将导致整个自定义类别从跳转列表中被省略。The list of removed items can be obtained using 可以使用app.getJumpListSettings()
.app.getJumpListSettings()
获取已删除项目的列表。
Note: The maximum length of a Jump List item's 跳转列表项的description
property is 260 characters. description
属性的最大长度为260个字符。Beyond this limit, the item will not be added to the Jump List, nor will it be displayed.超过此限制,该项目将不会添加到跳转列表中,也不会显示。
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',
icon: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
icon: 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
Record<any, any> (optional) -A JSON object containing additional data to send to the first instance.一个JSON对象,包含要发送到第一个实例的附加数据。
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.如果它未能获得锁,您可以假设您的应用程序的另一个实例已经在使用锁运行,然后立即退出。
I.e. This method returns 如果您的进程是应用程序的主要实例,并且您的应用程序应该继续加载,则此方法返回true
if your process is the primary instance of your application and your app should continue loading. true
。It returns 如果您的进程在将其参数发送到另一个已获取锁的实例时应立即退出,则返回false
if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock.false
。
On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the 在macOS上,当用户试图在Finder中打开应用程序的第二个实例时,系统会自动强制执行单个实例,并为此发出open-file
and open-url
events will be emitted for that. open-file
和open-url
事件。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 } = 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()
}
})
// Create myWindow, load the rest of the app, etc...
app.whenReady().then(() => {
myWindow = createWindow()
})
}
app.hasSingleInstanceLock()
Returns 返回boolean
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.requestSingleInstanceLock()
请求锁定,并使用app.releaseSingleInstanceLock()
释放
app.releaseSingleInstanceLock()
Releases all locks that were created by 释放requestSingleInstanceLock
. requestSingleInstanceLock
创建的所有锁。This will allow multiple instances of the application to once again run side by side.这将允许应用程序的多个实例再次并行运行。
app.setUserActivity(type, userInfo[, webpageURL])
macOS
type
string -Uniquely identifies the activity.唯一标识活动。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。userInfo
any -App-specific state to store for use by another device.要存储以供其他设备使用的应用程序特定状态。webpageURL
string (optional) -The webpage to load in a browser if no suitable app is installed on the resuming device.如果恢复设备上没有安装合适的应用程序,则要在浏览器中加载的网页。The scheme must be方案必须是http
orhttps
.http
或https
。
Creates an 创建NSUserActivity
and sets it as the current activity. NSUserActivity
并将其设置为当前活动。The activity is eligible for Handoff to another device afterward.活动之后有资格切换到另一个设备。
app.getCurrentActivityType()
macOS
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
string -Uniquely identifies the activity.唯一标识活动。Maps to NSUserActivity.activityType.映射到NSUserActivity.activityType。userInfo
any -App-specific state to store for use by another device.要存储以供其他设备使用的应用程序特定状态。
Updates the current activity if its type matches 如果当前活动的类型与type
, merging the entries from userInfo
into its current userInfo
dictionary.type
匹配,则更新当前活动,将userInfo
中的条目合并到其当前userInfo
字典中。
app.setAppUserModelId(id)
Windows
id
string
Changes the Application User Model ID to 将应用程序用户模型ID更改为id
.id
。
app.setActivationPolicy(policy)
macOS
policy
string -Can be 'regular', 'accessory', or 'prohibited'.可以是'regular'、'accessory'或'prohibited'。
Sets the activation policy for a given app.设置给定应用程序的激活策略。
Activation policy types:激活策略类型:
- 'regular' -
The application is an ordinary app that appears in the Dock and may have a user interface.该应用程序是一个出现在Dock中的普通应用程序,可能有一个用户界面。 - 'accessory' -
The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows.该应用程序不会出现在Dock中,也没有菜单栏,但它可以通过编程或单击其中一个窗口来激活。 - 'prohibited' -
The application doesn’t appear in the Dock and may not create windows or be activated.该应用程序不会出现在Dock中,可能不会创建窗口或被激活。
app.importCertificate(options, callback)
Linux
callback
Functionresult
Integer -Result of import.导入的结果。
Imports the certificate in pkcs12 format into the platform certificate store. 将pkcs12格式的证书导入到平台证书存储中。根据Chromium net_error_list,使用导入操作的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.result
调用callback
,值为0
表示成功,而任何其他值表示失败。
app.configureHostResolver(options)
Configures host resolution (DNS and DNS-over-HTTPS). 配置主机解析(DNS和HTTPS上的DNS)。By default, the following resolvers will be used, in order:默认情况下,将按顺序使用以下解析器:
DNS-over-HTTPS, if the DNS provider supports it, thenHTTPS上的DNS,如果DNS提供商支持它,那么the built-in resolver (enabled on macOS only by default), then内置解析器(仅在macOS上默认启用),然后the system's resolver (e.g.系统的解析器(例如getaddrinfo
).getaddrinfo
)。
This can be configured to either restrict usage of non-encrypted DNS (可以将其配置为限制使用未加密的DNS(secureDnsMode: "secure"
), or disable DNS-over-HTTPS (secureDnsMode: "off"
). secureDnsMode: "secure"
),或禁用HTTPS上的DNS(secureDnsMode: "off"
)。It is also possible to enable or disable the built-in resolver.也可以启用或禁用内置解析器。
To disable insecure DNS, you can specify a 要禁用不安全的DNS,可以将secureDnsMode
of "secure"
. secureDnsMode
指定为"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.如果您这样做,您应该确保提供一个使用HTTPS服务器的DNS列表,以防用户的DNS配置不包括支持DoH的提供商。
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: [
'https://cloudflare-dns.com/dns-query'
]
})
This API must be called after the 必须在发出ready
event is emitted.ready
事件之后调用此API。
app.disableHardwareAcceleration()
Disables hardware acceleration for current app.禁用当前应用程序的硬件加速。
This method can only be called before app is ready.此方法只能在应用程序准备就绪之前调用。
app.disableDomainBlockingFor3DAPIs()
By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. 默认情况下,如果GPU进程过于频繁地崩溃,Chromium会禁用3D API(例如WebGL),直到按域重新启动。This function disables that behavior.此函数将禁用该行为。
This method can only be called before app is ready.此方法只能在应用程序准备就绪之前调用。
app.getAppMetrics()
Returns ProcessMetric[]: Array of 返回ProcessMetric[]:ProcessMetric
objects that correspond to memory and CPU usage statistics of all the processes associated with the app.ProcessMetric
对象的数组,这些对象对应于与应用程序关联的所有进程的内存和CPU使用情况统计信息。
app.getGPUFeatureStatus()
Returns GPUFeatureStatus - The Graphics Feature Status from 返回GPUFeatureStatus - 来自chrome://gpu/
.chrome://gpu/
的图形功能状态。
Note: This information is only usable after the 此信息仅在发出gpu-info-update
event is emitted.gpu-info-update
事件后可用。
app.getGPUInfo(infoType)
infoType
string -Can be可以是basic
orcomplete
.basic
,也可以是complete
。
Returns 返回Promise<unknown>
For 对于等于infoType
equal to complete
: Promise is fulfilled with Object
containing all the GPU Information as in chromium's GPUInfo object. complete
的infoType
:Promise是通过包含chrome的GPUInfo对象中所有GPU信息的Object
来实现的。This includes the version and driver information that's shown on 这包括上显示的版本和驱动程序信息chrome://gpu
page.chrome://gpu
页
For 对于等于infoType
equal to basic
: Promise is fulfilled with Object
containing fewer attributes than when requested with complete
. basic
的infoType
:Promise是用Object实现的,与用complete
请求时相比,Object
包含的属性更少。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'
}
Using 如果只需要basic
should be preferred if only basic information like vendorId
or driverId
is needed.vendorId
或driverId
等基本信息,则应优先使用basic
。
app.setBadgeCount([count])
Linux macOS
count
Integer (optional) -If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications).如果提供了值,请将徽章设置为提供的值,否则,在macOS上,显示一个纯白点(例如未知数量的通知)。On Linux, if a value is not provided the badge will not display.在Linux上,如果没有提供值,徽章将不会显示。
Returns 返回boolean
- Whether the call succeeded.呼叫是否成功。
Sets the counter badge for current app. Setting the count to 设置当前应用程序的计数器徽章。将计数设置为0
will hide the badge.0
将隐藏徽章。
On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.在macOS上,它显示在dock图标上。在Linux上,它只适用于Unity启动器。
Note: Unity launcher requires a Unity启动器需要一个.desktop
file to work. .desktop
文件才能工作。For more information, please read the Unity integration documentation.有关更多信息,请阅读Unity集成文档。
app.getBadgeCount()
Linux macOS
Returns 返回Integer
- The current value displayed in the counter badge.计数器徽章中显示的当前值。
app.isUnityRunning()
Linux
Returns 返回boolean
- Whether the current desktop environment is Unity launcher.当前桌面环境是否为Unity启动器。
app.getLoginItemSettings([options])
macOS Windows
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.app.setLoginItemSettings
提供了path
和args
选项,那么您需要在此处传递相同的参数才能正确设置openAtLogin
。
Returns 返回Object
:Object
:
openAtLogin
boolean -如果应用程序设置为在登录时打开,则为true
if the app is set to open at login.true
。openAsHidden
boolean macOS -如果应用程序设置为在登录时以隐藏方式打开,则为true
if the app is set to open as hidden at login.true
。This setting is not available on MAS builds.此设置在MAS生成上不可用。wasOpenedAtLogin
boolean macOS -如果应用程序在登录时自动打开,则为true
if the app was opened at login automatically.true
。This setting is not available on MAS builds.此设置在MAS生成上不可用。wasOpenedAsHidden
boolean macOS -如果应用程序是作为隐藏登录项打开的,则为true
if the app was opened as a hidden login item.true
。This indicates that the app should not open any windows at startup.这表示应用程序在启动时不应打开任何窗口。This setting is not available on MAS builds.此设置在MAS生成上不可用。restoreState
boolean macOS -如果应用程序是作为登录项打开的,应该从上一个会话恢复状态,则为true
if the app was opened as a login item that should restore the state from the previous session.true
。This indicates that the app should restore the windows that were open the last time the app was closed.这表示应用程序应恢复上次关闭应用程序时打开的窗口。This setting is not available on MAS builds.此设置在MAS生成上不可用。executableWillLaunchAtLogin
boolean Windows -如果应用程序设置为在登录时打开,并且其运行密钥未被停用,则为true
if app is set to open at login and its run key is not deactivated.true
。This differs from这与openAtLogin
as it ignores theargs
option, this property will be true if the given executable would be launched at login with any arguments.openAtLogin
不同,因为它忽略了args
选项,如果给定的可执行文件在登录时使用任何参数启动,则此属性将为true
。launchItems
Object[]Windowsname
stringWindows -name value of a registry entry.注册表项的名称值。path
stringWindows -The executable to an app that corresponds to a registry entry.对应于注册表项的应用程序的可执行文件。args
string[]Windows -the command-line arguments to pass to the executable.要传递给可执行文件的命令行参数。scope
stringWindows -one ofuser
ormachine
.user
或machine
之一。Indicates whether the registry entry is under指示注册表项是在HKEY_CURRENT USER
orHKEY_LOCAL_MACHINE
.HKEY_CURRENT USER
还是HKEY_LOCAL_MACHINE
下。enabled
boolean Windows -如果应用程序注册表项已批准启动,因此在任务管理器和Windows设置中显示为true
if the app registry key is startup approved and therefore shows asenabled
in Task Manager and Windows settings.enabled
,则为true
。
app.setLoginItemSettings(settings)
macOS Windows
settings
ObjectopenAtLogin
boolean (optional) -true
to open the app at login,false
to remove the app as a login item.true
表示在登录时打开应用程序,false
表示将应用程序作为登录项删除。Defaults to默认为false
.false
。openAsHidden
boolean (optional) macOS -true
to open the app as hidden.true
以隐藏方式打开应用程序。Defaults to默认为false
.false
。The user can edit this setting from the System Preferences so用户可以从系统首选项编辑此设置,因此在打开应用程序时应检查app.getLoginItemSettings().wasOpenedAsHidden
should be checked when the app is opened to know the current value.app.getLoginItemSettings().wasOpenedAsHidden
以了解当前值。This setting is not available on MAS builds.此设置在MAS生成上不可用。path
string (optional) Windows -The executable to launch at login.登录时要启动的可执行文件。Defaults to默认为process.execPath
.process.execPath
。args
string[] (optional) Windows -The command-line arguments to pass to the executable.要传递给可执行文件的命令行参数。Defaults to an empty array.默认为空数组。Take care to wrap paths in quotes.注意将路径用引号括起来。enabled
boolean (optional) Windows -true
will change the startup approved registry key andenable / disable
the App in Task Manager and Windows Settings.true
将更改启动批准的注册表项,并在任务管理器和Windows设置中enable / disable
应用程序。Defaults to默认为true
.true
。name
string (optional) Windows -value name to write into registry.要写入注册表的值名称。Defaults to the app's AppUserModelId().默认为应用程序的AppUserModelId()
。Set the app's login item settings.设置应用程序的登录项目设置。
To work with Electron's 要在使用Squirrel的Windows上使用Electron的autoUpdater
on Windows, which uses Squirrel, you'll want to set the launch path to Update.exe, and pass arguments that specify your application name. autoUpdater
,您需要将启动路径设置为Updateexe,并传递指定应用程序名称的参数。For example:例如:
const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)
app.setLoginItemSettings({
openAtLogin: true,
path: updateExe,
args: [
'--processStart', `"${exeName}"`,
'--process-start-args', `"--hidden"`
]
})
app.isAccessibilitySupportEnabled()
macOS Windows
Returns 返回boolean
- 如果启用了Chrome的辅助功能支持,则为true
if Chrome's accessibility support is enabled, false
otherwise. true
,否则为false
。This API will return 如果检测到屏幕阅读器等辅助技术的使用,则此API将返回true
if the use of assistive technologies, such as screen readers, has been detected. true
。See https://www.chromium.org/developers/design-documents/accessibility for more details.请参阅https://www.chromium.org/developers/design-documents/accessibility以了解更多详细信息。
app.setAccessibilitySupportEnabled(enabled)
macOS Windows
enabled
boolean -Enable or disable accessibility tree rendering启用或禁用辅助功能树呈现
Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. 手动启用Chrome的辅助功能支持,允许在应用程序设置中向用户公开辅助功能开关。See Chromium's accessibility docs for more details. 有关更多详细信息,请参阅Chromium的辅助功能文档。Disabled by default.默认情况下已禁用。
This API must be called after the 必须在发出ready
event is emitted.ready
事件之后调用此API。
Note: Rendering accessibility tree can significantly affect the performance of your app. 渲染辅助功能树会显著影响应用程序的性能。It should not be enabled by default.默认情况下不应启用它。
app.showAboutPanel()
Show the app's about panel options. 显示应用程序的关于面板选项。These options can be overridden with 这些选项可以用app.setAboutPanelOptions(options)
.app.setAboutPanelOptions(options)
覆盖。
app.setAboutPanelOptions(options)
Set the about panel options. 设置“关于”面板选项。This will override the values defined in the app's 这将覆盖macOS上应用程序的.plist
file on macOS. .plist
文件中定义的值。See the Apple docs for more details. 有关更多详细信息,请参阅Apple文档。On Linux, values must be set in order to be shown; there are no defaults.在Linux上,必须设置值才能显示;没有默认值。
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. credits
,但仍希望在应用程序中显示信用,AppKit将在NSBundle类方法main返回的bundle中按顺序查找名为“Credits.html”、“Credits.rtf”和“Credits.rtfd”的文件。The first file found is used, and if none is found, the info area is left blank. 使用找到的第一个文件,如果没有找到,则信息区域为空。See Apple documentation for more information.有关更多信息,请参阅Apple文档。
app.isEmojiPanelSupported()
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
string -The base64 encoded security scoped bookmark data returned by thedialog.showOpenDialog
ordialog.showSaveDialog
methods.dialog.showOpenDialog
或dialog.showSaveDialog
方法返回的base64编码的安全范围书签数据。
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.如果你不记得停止访问书签,内核资源将被泄露,你的应用程序将完全失去访问沙盒之外的能力,直到你的应用重新启动。
// Start accessing the file.
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data)
// You can now access the file outside of the sandbox 🎉
// Remember to stop accessing the file once you've finished with it.
stopAccessingSecurityScopedResource()
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. 通过这种方法,为Mac应用商店打包的Electron应用程序可以访问其沙箱之外的用户选择的文件。See Apple's documentation for a description of how this system works.有关此系统如何工作的描述,请参阅苹果公司的文档。
app.enableSandbox()
Enables full sandbox mode on the app. 在应用程序上启用完全沙箱模式。This means that all renderers will be launched sandboxed, regardless of the value of the 这意味着,无论WebPreferences中sandbox
flag in WebPreferences.sandbox
标志的值如何,所有渲染器都将启动沙箱。
This method can only be called before app is ready.此方法只能在应用程序准备就绪之前调用。
app.isInApplicationsFolder()
macOS
Returns 返回boolean
- Whether the application is currently running from the systems Application folder. 应用程序当前是否在系统应用程序文件夹中运行。Use in combination with 与app.moveToApplicationsFolder()
app.moveToApplicationsFolder()
组合使用
app.moveToApplicationsFolder([options])
macOS
Returns 返回boolean
- Whether the move was successful. 此举是否成功。Please note that if the move is successful, your application will quit and relaunch.请注意,如果移动成功,您的应用程序将退出并重新启动。
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.如果您希望允许用户确认操作,可以使用dialogAPI进行确认。
NOTE: This method throws errors if anything other than the user causes the move to fail. 如果除用户之外的任何其他原因导致移动失败,此方法将抛出错误。For instance if the user cancels the authorization dialog, this method returns false. 例如,如果用户取消了授权对话框,此方法将返回false
。If we fail to perform the copy, then this method will throw an error. 如果我们无法执行复制,那么这个方法将抛出一个错误。The message in the error should be informative and tell you exactly what went wrong.错误中的信息应该是有信息的,并准确地告诉你出了什么问题。
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 pre-existing 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.false
将确保不采取进一步的操作,返回true
将导致默认行为和方法继续。
For example:
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
Returns 返回boolean
- whether Secure Keyboard Entry
is enabled.boolean
- 是否启用了安全键盘输入
。
By default this API will return 默认情况下,此API将返回false
.false
。
app.setSecureKeyboardEntryEnabled(enabled)
macOS
enabled
boolean -Enable or disable启用或禁用Secure Keyboard Entry
安全键盘输入
Set the 设置应用程序中启用的Secure Keyboard Entry
is enabled in your application.安全键盘输入
。
By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.通过使用此API,可以防止密码等重要信息和其他敏感信息被其他进程截获。
See Apple's documentation for more details.有关更多详细信息,请参阅苹果公司的文档。
Note: Enable 仅在需要时启用Secure Keyboard Entry
only when it is needed and disable it when it is no longer needed.安全键盘输入
,在不再需要时禁用安全键盘输入。
Properties属性
app.accessibilitySupportEnabled
macOS Windows
A 一个boolean
property that's true
if Chrome's accessibility support is enabled, false
otherwise. boolean
属性,如果启用Chrome的可访问性支持,则为true
,否则为false
。This property will be 如果检测到使用了辅助技术(如屏幕阅读器),则此属性为true
if the use of assistive technologies, such as screen readers, has been detected. true
。Setting this property to 手动将此属性设置为true
manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings.true
将启用Chrome的辅助功能支持,允许开发人员在应用程序设置中将辅助功能开关公开给用户。
See Chromium's accessibility docs for more details. 有关更多详细信息,请参阅Chromium的辅助功能文档。Disabled by default.默认情况下已禁用。
This API must be called after the 必须在发出ready
event is emitted.ready
事件之后调用此API。
Note: Rendering accessibility tree can significantly affect the performance of your app. 渲染辅助功能树会显著影响应用程序的性能。It should not be enabled by default.默认情况下不应启用它。
app.applicationMenu
A Menu | null
property that returns Menu if one has been set and null
otherwise. Menu|null
属性,如果设置了菜单,则返回Menu,否则返回null
。Users can pass a Menu to set this property.用户可以传递Menu来设置此属性。
app.badgeCount
Linux macOS
An Integer
property that returns the badge count for current app. Integer
属性,用于返回当前应用程序的徽章计数。Setting the count to 将计数设置为0
will hide the badge.0
将隐藏徽章。
On macOS, setting this with any nonzero integer shows on the dock icon. 在macOS上,使用任何非零整数进行设置都会显示在dock图标上。On Linux, this property only works for Unity launcher.在Linux上,此属性仅适用于Unity启动器。
Note: Unity launcher requires a Unity启动器需要一个.desktop
file to work. .desktop
文件才能工作。For more information, please read the Unity integration documentation.有关更多信息,请阅读Unity集成文档。
Note: On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect.在macOS上,您需要确保您的应用程序具有显示此属性生效通知的权限。
app.commandLine
Readonly
A CommandLine object that allows you to read and manipulate the command line arguments that Chromium uses.一个CommandLine对象,允许您读取和操作Chromium使用的命令行参数。
app.dock
macOS Readonly
A Dock | Dock | undefined
object that allows you to perform actions on your app icon in the user's dock on macOS.undefined
的对象,允许您在macOS上的用户Dock中对应用程序图标执行操作。
app.isPackaged
Readonly
A 一个boolean
property that returns true
if the app is packaged, false
otherwise. boolean
性,如果应用程序已打包,则返回true
,否则返回false
。For many apps, this property can be used to distinguish development and production environments.对于许多应用程序,此属性可用于区分开发环境和生产环境。
app.name
A 一个string
property that indicates the current application's name, which is the name in the application's package.json
file.string
属性,指示当前应用程序的名称,即应用程序的package.json
文件中的名称。
Usually the 根据npm模块规范,name
field of package.json
is a short lowercase name, according to the npm modules spec. package.json
的name
字段通常是一个小写的短名称。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.productName
字段,这是您的应用程序的大写全名,它将优先于Electron的name
。
app.userAgentFallback
A 作为用户代理字符串的string
which is the user agent string Electron will use as a global fallback.string
Electron将用作全局回退。
This is the user agent that will be used when no user agent is set at the 这是在webContents
or session
level. webContents
或session
级别未设置用户代理时将使用的用户代理。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.runningUnderRosettaTranslation
macOS Readonly Deprecated
A 一个boolean
which when true
indicates that the app is currently running under the Rosetta Translator Environment.boolean
,当为true
时,表示应用程序当前正在Rosetta Translator环境下运行。
You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly.当用户在Rosetta下错误地运行x64版本时,您可以使用此属性提示用户下载应用程序的arm64版本。
Deprecated: This property is superceded by the 此属性被runningUnderARM64Translation
property which detects when the app is being translated to ARM64 in both macOS and Windows.runningUnderARM64Translation
属性取代,该属性检测应用程序何时在macOS和Windows中被转换为ARM64。
app.runningUnderARM64Translation
Readonly macOS Windows
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).boolean
,当为true
时,表示应用程序当前正在ARM64翻译器(如macOS Rosetta翻译器环境或Windows WOW)下运行。
You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly.当用户在Rosetta下错误地运行x64版本时,您可以使用此属性提示用户下载应用程序的arm64版本。