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
app
对象发出以下事件:
¥The app
object emits the following events:
事件:'will-finish-launching'
¥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.
事件:'ready'
¥Event: 'ready'
返回:
¥Returns:
-
event
事件¥
event
Event -
launchInfo
Record<string,任何> | NotificationResponse macOS¥
launchInfo
Record<string, any> | NotificationResponse 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,请确保它在主进程的顶层上下文中同步调用。
¥Note: The ready
event is only fired after the main process has finished running the first
tick of the event loop. If an Electron API needs to be called before the ready
event, ensure
that it is called synchronously in the top-level context of the main process.
事件:'window-all-closed'
¥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.
事件:'before-quit'
¥Event: 'before-quit'
返回:
¥Returns:
-
event
事件¥
event
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
。
¥Note: If application quit was initiated by autoUpdater.quitAndInstall()
,
then before-quit
is emitted after emitting close
event on all windows and
closing them.
注意:在 Windows 上,如果应用由于系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
¥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.
事件:'will-quit'
¥Event: 'will-quit'
返回:
¥Returns:
-
event
事件¥
event
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.
will-quit
和 window-all-closed
事件之间的差异请参阅 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 上,如果应用由于系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
¥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.
事件:'quit'
¥Event: 'quit'
返回:
¥Returns:
-
event
事件¥
event
Event -
exitCode
整数¥
exitCode
Integer
当应用退出时发出。
¥Emitted when the application is quitting.
注意:在 Windows 上,如果应用由于系统关闭/重新启动或用户注销而关闭,则不会发出此事件。
¥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.
事件:'open-file' macOS
¥Event: 'open-file' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
path
字符串¥
path
string
当用户想要使用应用打开文件时发出。当应用已经打开并且操作系统想要重用该应用来打开文件时,通常会发出 open-file
事件。当文件被拖放到扩展坞上并且应用尚未运行时,也会发出 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.
事件:'open-url' macOS
¥Event: 'open-url' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
url
字符串¥
url
string
当用户想要使用应用打开 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.
事件:'activate' macOS
¥Event: 'activate' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
hasVisibleWindows
布尔值¥
hasVisibleWindows
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.
事件:'did-become-active' macOS
¥Event: 'did-become-active' macOS
返回:
¥Returns:
-
event
事件¥
event
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.
事件:'did-resign-active' macOS
¥Event: 'did-resign-active' macOS
返回:
¥Returns:
-
event
事件¥
event
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.
事件:'continue-activity' macOS
¥Event: 'continue-activity' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
type
字符串 - 标识活动的字符串。映射到NSUserActivity.activityType
。¥
type
string - A string identifying the activity. Maps toNSUserActivity.activityType
. -
userInfo
未知 - 包含由另一台设备上的活动存储的特定于应用的状态。¥
userInfo
unknown - Contains app-specific state stored by the activity on another device. -
details
对象¥
details
Object-
webpageURL
字符串(可选) - 标识另一台设备上的活动访问的网页 URL 的字符串(如果有)。¥
webpageURL
string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available.
-
当来自不同设备的活动想要恢复时,在 不可触摸 期间发出。如果你想处理此事件,请致电 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.
事件:'will-continue-activity' macOS
¥Event: 'will-continue-activity' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
type
字符串 - 标识活动的字符串。映射到NSUserActivity.activityType
。¥
type
string - A string identifying the activity. Maps toNSUserActivity.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.
事件:'continue-activity-error' macOS
¥Event: 'continue-activity-error' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
type
字符串 - 标识活动的字符串。映射到NSUserActivity.activityType
。¥
type
string - A string identifying the activity. Maps toNSUserActivity.activityType
. -
error
字符串 - 包含错误本地化描述的字符串。¥
error
string - A string with the error's localized description.
当来自不同设备的活动无法恢复时在 不可触摸 期间发出。
¥Emitted during Handoff when an activity from a different device fails to be resumed.
事件:'activity-was-continued' macOS
¥Event: 'activity-was-continued' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
type
字符串 - 标识活动的字符串。映射到NSUserActivity.activityType
。¥
type
string - A string identifying the activity. Maps toNSUserActivity.activityType
. -
userInfo
未知 - 包含由活动存储的特定于应用的状态。¥
userInfo
unknown - Contains app-specific state stored by the activity.
在该设备的活动在另一设备上成功恢复后,在 不可触摸 期间发出。
¥Emitted during Handoff after an activity from this device was successfully resumed on another one.
事件:'update-activity-state' macOS
¥Event: 'update-activity-state' macOS
返回:
¥Returns:
-
event
事件¥
event
Event -
type
字符串 - 标识活动的字符串。映射到NSUserActivity.activityType
。¥
type
string - A string identifying the activity. Maps toNSUserActivity.activityType
. -
userInfo
未知 - 包含由活动存储的特定于应用的状态。¥
userInfo
unknown - Contains app-specific state stored by the activity.
当 不可触摸 即将在另一台设备上恢复时发出。如果需要更新要转移的状态,应该立即调用 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.
事件:'new-window-for-tab' macOS
¥Event: 'new-window-for-tab' macOS
返回:
¥Returns:
-
event
事件¥
event
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
事件:'browser-window-blur'
¥Event: 'browser-window-blur'
返回:
¥Returns:
-
event
事件¥
event
Event -
window
BrowserWindow
当 browserWindow 变得模糊时发出。
¥Emitted when a browserWindow gets blurred.
事件:'browser-window-focus'
¥Event: 'browser-window-focus'
返回:
¥Returns:
-
event
事件¥
event
Event -
window
BrowserWindow
当 browserWindow 获得焦点时发出。
¥Emitted when a browserWindow gets focused.
事件:'browser-window-created'
¥Event: 'browser-window-created'
返回:
¥Returns:
-
event
事件¥
event
Event -
window
BrowserWindow
创建新的 browserWindow 时发出。
¥Emitted when a new browserWindow is created.
事件:'web-contents-created'
¥Event: 'web-contents-created'
返回:
¥Returns:
-
event
事件¥
event
Event -
webContents
WebContents
创建新的 webContents 时发出。
¥Emitted when a new webContents is created.
事件:'certificate-error'
¥Event: 'certificate-error'
返回:
¥Returns:
-
event
事件¥
event
Event -
webContents
WebContents -
url
字符串¥
url
string -
error
字符串 - 错误代码¥
error
string - The error code -
certificate
证书¥
certificate
Certificate -
callback
函数¥
callback
Function-
isTrusted
布尔值 - 是否将证书视为可信¥
isTrusted
boolean - Whether to consider the certificate as trusted
-
-
isMainFrame
布尔值¥
isMainFrame
boolean
当无法验证 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)
}
})
事件:'select-client-certificate'
¥Event: 'select-client-certificate'
返回:
¥Returns:
-
event
事件¥
event
Event -
webContents
WebContents -
url
URL -
certificateList
Certificate[] -
callback
函数¥
callback
Function-
certificate
证书(可选)¥
certificate
Certificate (optional)
-
请求客户端证书时发出。
¥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])
})
事件:'login'
¥Event: 'login'
返回:
¥Returns:
-
event
事件¥
event
Event -
webContents
WebContents(可选)¥
webContents
WebContents (optional) -
authenticationResponseDetails
对象¥
authenticationResponseDetails
Object-
url
URL -
pid
数字¥
pid
number
-
-
authInfo
对象¥
authInfo
Object-
isProxy
布尔值¥
isProxy
boolean -
scheme
字符串¥
scheme
string -
host
字符串¥
host
string -
port
整数¥
port
Integer -
realm
字符串¥
realm
string
-
-
callback
函数¥
callback
Function-
username
字符串(可选)¥
username
string (optional) -
password
字符串(可选)¥
password
string (optional)
-
当 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.
事件:'gpu-info-update'
¥Event: 'gpu-info-update'
每当 GPU 信息更新时发出。
¥Emitted whenever there is a GPU info update.
事件:'render-process-gone'
¥Event: 'render-process-gone'
返回:
¥Returns:
-
event
事件¥
event
Event -
webContents
WebContents -
details
渲染进程消失详细信息¥
details
RenderProcessGoneDetails
当渲染器进程意外消失时发出。这通常是因为它坠毁或死亡。
¥Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
事件:'child-process-gone'
¥Event: 'child-process-gone'
返回:
¥Returns:
-
event
事件¥
event
Event -
details
对象¥
details
Object-
type
字符串 - 工艺类型。以下值之一:¥
type
string - Process type. One of the following values:-
Utility
-
Zygote
-
Sandbox helper
-
GPU
-
Pepper Plugin
-
Pepper Plugin Broker
-
Unknown
-
-
reason
字符串 - 子进程消失的原因。可能的值:¥
reason
string - The reason the child process is gone. Possible values:-
clean-exit
- 进程退出,退出代码为零¥
clean-exit
- Process exited with an exit code of zero -
abnormal-exit
- 进程以非零退出代码退出¥
abnormal-exit
- Process exited with a non-zero exit code -
killed
- 进程被发送 SIGTERM 或以其他方式从外部终止¥
killed
- Process was sent a SIGTERM or otherwise killed externally -
crashed
- 进程崩溃¥
crashed
- Process crashed -
oom
- 进程内存不足¥
oom
- Process ran out of memory -
launch-failed
- 进程从未成功启动¥
launch-failed
- Process never successfully launched -
integrity-failure
- Windows 代码完整性检查失败¥
integrity-failure
- Windows code integrity checks failed
-
-
exitCode
数字 - 进程的退出代码(例如,在 posix 上来自 waitpid 的状态,在 Windows 上来自 GetExitCodeProcess)。¥
exitCode
number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows). -
serviceName
字符串(可选) - 进程的非本地化名称。¥
serviceName
string (optional) - The non-localized name of the process. -
name
字符串(可选) - 进程的名称。实用程序示例:Audio Service
、Content Decryption Module Service
、Network Service
、Video Capture
等¥
name
string (optional) - The name of the process. Examples for utility:Audio Service
,Content Decryption Module Service
,Network Service
,Video Capture
, etc.
-
当子进程意外消失时发出。这通常是因为它坠毁或死亡。它不包括渲染器进程。
¥Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes.
事件:'accessibility-support-changed' macOS Windows
¥Event: 'accessibility-support-changed' macOS Windows
返回:
¥Returns:
-
event
事件¥
event
Event -
accessibilitySupportEnabled
布尔值 - 当启用 Chrome 的辅助功能支持时为true
,否则为false
。¥
accessibilitySupportEnabled
boolean -true
when Chrome's accessibility support is enabled,false
otherwise.
当 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.
事件:'session-created'
¥Event: 'session-created'
返回:
¥Returns:
当 Electron 创建一个新的 session
时发出。
¥Emitted when Electron has created a new session
.
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
事件:'second-instance'
¥Event: 'second-instance'
返回:
¥Returns:
-
event
事件¥
event
Event -
argv
字符串[] - 第二个实例的命令行参数的数组¥
argv
string[] - An array of the second instance's command line arguments -
workingDirectory
字符串 - 第二个实例的工作目录¥
workingDirectory
string - The second instance's working directory -
additionalData
未知 - 从第二个实例传递的附加数据的 JSON 对象¥
additionalData
unknown - A JSON object of additional data passed from the second instance
当执行第二个实例并调用 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
is an Array of the second instance's command line arguments,
and workingDirectory
is its current working directory. Usually
applications respond to this by making their primary window focused and
non-minimized.
注意:argv
不会与传递给第二个实例的参数列表完全相同。顺序可能会改变,并且可能会附加其他参数。如果你需要保持完全相同的参数,建议使用 additionalData
。
¥Note: argv
will not be exactly the same list of arguments as those passed
to the second instance. The order might change and additional arguments might be appended.
If you need to maintain the exact same arguments, it's advised to use additionalData
instead.
注意:如果第二个实例由与第一个实例不同的用户启动,则 argv
数组将不包含参数。
¥Note: If the second instance is started by a different user than the first, the argv
array will not include the arguments.
该事件保证在 app
的 ready
事件发出后发出。
¥This event is guaranteed to be emitted after the ready
event of app
gets emitted.
注意:Chromium 可能会添加额外的命令行参数,例如 --original-process-start-time
。
¥Note: Extra command line arguments might be added by Chromium,
such as --original-process-start-time
.
方法
¥Methods
app
对象有以下方法:
¥The app
object has the following methods:
注意:有些方法仅在特定操作系统上可用,并如此标记。
¥Note: Some methods are only available on specific operating systems and are labeled as such.
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
Integer (optional)
立即退出并显示 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 current instance exits.
默认情况下,新实例将使用与当前实例相同的工作目录和命令行参数。当指定 args
时,args
将作为命令行参数传递。当指定 execPath
时,重新启动时将执行 execPath
而不是当前应用。
¥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. When execPath
is specified, the
execPath
will be executed for relaunch instead of 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 for multiple times, multiple instances will be
started after current instance exited.
立即重新启动当前实例并向新实例添加新的命令行参数的示例:
¥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()
返回 boolean
- 如果 Electron 已完成初始化,则为 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
返回 boolean
- 如果应用(包括其所有窗口)被隐藏(例如使用 Command-H
),则为 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
字符串(可选) - 日志的自定义路径。一定是绝对的。¥
path
string (optional) - A custom path for your logs. Must be absolute.
设置或创建应用日志的目录,然后可以使用 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
字符串 - 你可以通过名称请求以下路径:¥
name
string - You can request the following paths by the name:-
home
用户的主目录。¥
home
User's home directory. -
appData
每用户应用数据目录,默认情况下指向:¥
appData
Per-user application data directory, which by default points to:-
Windows 上的
%APPDATA%
¥
%APPDATA%
on Windows -
Linux 上的
$XDG_CONFIG_HOME
或~/.config
¥
$XDG_CONFIG_HOME
or~/.config
on Linux -
macOS 上的
~/Library/Application Support
¥
~/Library/Application Support
on macOS
-
-
userData
用于存储应用配置文件的目录,默认情况下是附加应用名称的appData
目录。按照惯例,存储用户数据的文件应该写入此目录,不建议在此写入大文件,因为某些环境可能会将此目录备份到云存储。¥
userData
The directory for storing your app's configuration files, which by default is theappData
directory appended with your app's name. 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
存放Session
生成的数据的目录,如 localStorage、cookies、磁盘缓存、下载的字典、网络状态、devtools 文件。默认情况下,它指向userData
。Chromium 可能会在这里写入非常大的磁盘缓存,因此如果你的应用不依赖 localStorage 或 cookie 等浏览器存储来保存用户数据,建议将此目录设置到其他位置,以避免污染userData
目录。¥
sessionData
The directory for storing data generated bySession
, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points touserData
. 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 theuserData
directory. -
temp
临时目录。¥
temp
Temporary directory. -
exe
当前的可执行文件。¥
exe
The current executable file. -
module
libchromiumcontent
库。¥
module
Thelibchromiumcontent
library. -
desktop
当前用户的桌面目录。¥
desktop
The current user's Desktop directory. -
documents
用户 "我的文件" 的目录。¥
documents
Directory for a user's "My Documents". -
downloads
用户下载的目录。¥
downloads
Directory for a user's downloads. -
music
用户音乐的目录。¥
music
Directory for a user's music. -
pictures
用户图片的目录。¥
pictures
Directory for a user's pictures. -
videos
用户视频的目录。¥
videos
Directory for a user's videos. -
recent
用户最近使用的文件的目录(仅限 Windows)。¥
recent
Directory for the user's recent files (Windows only). -
logs
应用日志文件夹的目录。¥
logs
Directory for your app's log folder. -
crashDumps
存储故障转储的目录。¥
crashDumps
Directory where crash dumps are stored.
-
返回 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')
,则会创建一个默认日志目录,相当于在不带 path
参数的情况下调用 app.setAppLogsPath()
。
¥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.getFileIcon(path[, options])
-
path
字符串¥
path
string
返回 Promise<NativeImage>
- 满足应用的图标,即 NativeImage。
¥Returns Promise<NativeImage>
- fulfilled with the app's icon, which is a NativeImage.
获取路径的关联图标。
¥Fetches a path's associated icon.
在 Windows 上,有 2 种图标:
¥On Windows, there a 2 kinds of icons:
-
与某些文件扩展名相关的图标,例如
.mp3
、.png
等。¥Icons associated with certain file extensions, like
.mp3
,.png
, etc. -
文件本身内的图标,如
.exe
、.dll
、.ico
。¥Icons inside the file itself, like
.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
字符串¥
name
string -
path
字符串¥
path
string
将 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
.
默认情况下,网页的 cookie 和缓存将存储在 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.
根据 npm 模块规范,通常 package.json
的 name
字段是一个短的小写名称。你通常还应该指定 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
字符串¥
name
string
覆盖当前应用的名称。
¥Overrides the current application's name.
注意:该函数覆盖 Electron 内部使用的名称;它不会影响操作系统使用的名称。
¥Note: This function overrides the name used internally by Electron; it does not affect the name that the OS uses.
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
文件夹。
¥Note: When distributing your packaged app, you have to also ship the
locales
folder.
注意:必须在 ready
事件发出后调用此 API。
¥Note: This API must be called after the ready
event is emitted.
注意:要查看此 API 与其他区域设置和语言 API 相比的示例返回值,请参阅 app.getPreferredSystemLanguages()
。
¥Note: To see example return values of this API compared to other locale and language APIs, see 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.
注意:当无法检测区域设置国家代码时,它返回空字符串。
¥Note: When unable to detect locale country code, it returns empty string.
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 使用数字、日期和时间的区域格式。
¥Windows 11 uses the regional format for numbers, dates, and times.
-
macOS Monterey 使用该区域来格式化数字、日期、时间以及选择要使用的货币符号。
¥macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use.
因此,此 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.
注意:必须在 ready
事件发出后调用此 API。
¥Note: This API must be called after the ready
event is emitted.
注意:要查看此 API 与其他区域设置和语言 API 相比的示例返回值,请参阅 app.getPreferredSystemLanguages()
。
¥Note: To see example return values of this API compared to other locale and language APIs, see 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
string
将 path
添加到最近的文档列表中。
¥Adds path
to the recent documents list.
该列表由操作系统管理。在 Windows 上,你可以从任务栏访问该列表,在 macOS 上,你可以从停靠菜单访问它。
¥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.setAsDefaultProtocolClient(protocol[, path, args])
-
protocol
字符串 - 你的协议名称,不带://
。例如,如果你希望应用处理electron://
链接,请使用electron
作为参数调用此方法。¥
protocol
string - The name of your protocol, without://
. For example, if you want your app to handleelectron://
links, call this method withelectron
as the parameter. -
path
字符串(可选) Windows - Electron 可执行文件的路径。默认为process.execPath
¥
path
string (optional) Windows - The path to the Electron executable. Defaults toprocess.execPath
-
args
字符串[](可选)Windows - 传递给可执行文件的参数。默认为空数组¥
args
string[] (optional) Windows - Arguments passed to the executable. Defaults to an empty array
返回 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 Packager 或使用文本编辑器编辑 info.plist
来更改文件。详情请参阅 苹果的文档。
¥Note: On macOS, you can only register protocols that have been added to
your app's info.plist
, which cannot be modified at runtime. However, you can
change the file during build time via Electron Forge,
Electron Packager, or by editing info.plist
with a text
editor. Please refer to Apple's documentation for details.
注意:在 Windows 应用商店环境中(当打包为 appx
时),此 API 将为所有调用返回 true
,但它设置的注册表项将无法被其他应用访问。为了将你的 Windows 应用商店应用注册为默认协议处理程序,你必须 在清单中声明协议。
¥Note: In a Windows Store environment (when packaged as an appx
) this API
will return true
for all calls but the registry key it sets won't be accessible
by other applications. In order to register your Windows Store application
as a default protocol handler you must declare the protocol in your manifest.
该 API 在内部使用 Windows 注册表和 LSSetDefaultHandlerForURLScheme
。
¥The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme
internally.
app.removeAsDefaultProtocolClient(protocol[, path, args])
macOS Windows
-
protocol
字符串 - 你的协议名称,不带://
。¥
protocol
string - The name of your protocol, without://
. -
path
字符串(可选) Windows - 默认为process.execPath
¥
path
string (optional) Windows - Defaults toprocess.execPath
-
args
字符串[](可选)Windows - 默认为空数组¥
args
string[] (optional) Windows - Defaults to an empty array
返回 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
字符串 - 你的协议名称,不带://
。¥
protocol
string - The name of your protocol, without://
. -
path
字符串(可选) Windows - 默认为process.execPath
¥
path
string (optional) Windows - Defaults toprocess.execPath
-
args
字符串[](可选)Windows - 默认为空数组¥
args
string[] (optional) Windows - Defaults to an empty array
返回 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
来验证这一点。详情请参阅 苹果的文档。
¥Note: On macOS, you can use this method to check if the app has been
registered as the default protocol handler for a protocol. You can also verify
this by checking ~/Library/Preferences/com.apple.LaunchServices.plist
on the
macOS machine. Please refer to
Apple's documentation for details.
该 API 在内部使用 Windows 注册表和 LSCopyDefaultHandlerForURLScheme
。
¥The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme
internally.
app.getApplicationNameForProtocol(url)
-
url
字符串 - 带有要检查的协议名称的 URL。与该系列中的其他方法不同,它接受整个 URL,至少包括://
(例如https://
)。¥
url
string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including://
at a minimum (e.g.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://
)。¥
url
string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including://
at a minimum (e.g.https://
).
返回 Promise<Object>
- 使用包含以下内容的对象进行解析:
¥Returns Promise<Object>
- Resolve with an object containing the following:
-
icon
NativeImage - 处理协议的应用的显示图标。¥
icon
NativeImage - the display icon of the app handling the protocol. -
path
字符串 - 处理协议的应用的安装路径。¥
path
string - installation path of the app handling the protocol. -
name
字符串 - 处理协议的应用的显示名称。¥
name
string - display name of the app handling the protocol.
此方法返回一个 promise,其中包含 URL 协议(也称为 URI 方案)的默认处理程序的应用名称、图标和路径。
¥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
添加到 Windows 跳转列表的 任务 类别中。
¥Adds tasks
to the Tasks category of the Jump List on Windows.
tasks
是 Task
对象的数组。
¥tasks
is an array of Task
objects.
返回 boolean
- 是否调用成功。
¥Returns boolean
- Whether the call succeeded.
注意:如果你想自定义跳转列表,请使用 app.setJumpList(categories)
。
¥Note: If you'd like to customize the Jump List even more use
app.setJumpList(categories)
instead.
app.getJumpListSettings()
Windows
返回 Object
:
¥Returns Object
:
-
minItems
整数 - 跳转列表中显示的最小项目数(有关该值的更详细说明,请参阅 MSDN 文档)。¥
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). -
removedItems
JumpListItem[] - 与用户已从跳转列表中的自定义类别中明确删除的项目相对应的JumpListItem
对象数组。在下次调用app.setJumpList()
时,不得将这些项目重新添加到跳转列表中,Windows 将不会显示包含任何已删除项目的任何自定义类别。¥
removedItems
JumpListItem[] - Array ofJumpListItem
objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the next call toapp.setJumpList()
, Windows will not display any custom category that contains any of the removed items.
app.setJumpList(categories)
Windows
-
categories
JumpListCategory[] |null
-JumpListCategory
对象数组。¥
categories
JumpListCategory[] |null
- Array ofJumpListCategory
objects.
返回 string
¥Returns string
设置或删除应用的自定义跳转列表,并返回以下字符串之一:
¥Sets or removes a custom Jump List for the application, and returns one of the following strings:
-
ok
- 没有出什么问题。¥
ok
- Nothing went wrong. -
error
- 发生一个或多个错误,启用运行时日志记录以找出可能的原因。¥
error
- One or more errors occurred, enable runtime logging to figure out the likely cause. -
invalidSeparatorError
- 尝试将分隔符添加到跳转列表中的自定义类别。仅在标准Tasks
类别中允许使用分隔符。¥
invalidSeparatorError
- An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standardTasks
category. -
fileTypeRegistrationError
- 尝试将文件链接添加到应用未注册处理的文件类型的跳转列表。¥
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
- 由于用户隐私或组策略设置,自定义类别无法添加到跳转列表。¥
customCategoryAccessDeniedError
- Custom categories can't be added to the Jump List due to user privacy or group policy settings.
如果 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
。
¥Note: If a JumpListCategory
object has neither the type
nor the name
property set then its type
is assumed to be tasks
. If the name
property
is set but the type
property is omitted then the type
is assumed to be
custom
.
注意:用户可以从自定义类别中删除项目,并且在下一次成功调用 app.setJumpList(categories)
之前,Windows 不允许将已删除的项目添加回自定义类别。任何在此之前将已删除的项目重新添加到自定义类别的尝试都将导致整个自定义类别从跳转列表中被忽略。可以使用 app.getJumpListSettings()
获取已删除项目的列表。
¥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)
. 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()
.
注意:跳转列表项的 description
属性的最大长度为 260 个字符。超出此限制,该项目将不会添加到跳转列表中,也不会显示。
¥Note: The maximum length of a Jump List item's description
property is
260 characters. 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',
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
记录<任意,任意>(可选) - 包含要发送到第一个实例的附加数据的 JSON 对象。¥
additionalData
Record<any, any> (optional) - A JSON object containing additional data to send to the first instance.
返回 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.
I.e.如果你的进程是应用的主实例并且你的应用应继续加载,则此方法返回 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
。¥
type
string - Uniquely identifies the activity. Maps toNSUserActivity.activityType
. -
userInfo
任意 - 存储供其他设备使用的应用特定状态。¥
userInfo
any - App-specific state to store for use by another device. -
webpageURL
字符串(可选) - 如果恢复设备上没有安装合适的应用,则在浏览器中加载的网页。该方案必须是http
或https
。¥
webpageURL
string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must behttp
orhttps
.
创建 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
。¥
type
string - Uniquely identifies the activity. Maps toNSUserActivity.activityType
. -
userInfo
任意 - 存储供其他设备使用的应用特定状态。¥
userInfo
any - App-specific state to store for use by another device.
如果当前活动的类型与 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
string
将 应用用户模型 ID 更改为 id
。
¥Changes the Application User Model ID to id
.
app.setActivationPolicy(policy)
macOS
-
policy
字符串 - 可以是 'regular'、'accessory' 或 'prohibited'。¥
policy
string - Can be 'regular', 'accessory', or 'prohibited'.
设置给定应用的激活策略。
¥Sets the activation policy for a given app.
激活策略类型:
¥Activation policy types:
-
'regular' - 该应用是出现在 Dock 中的普通应用,并且可能具有用户界面。
¥'regular' - The application is an ordinary app that appears in the Dock and may have a user interface.
-
'accessory' - 该应用不会出现在 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.
-
'prohibited' - 该应用不会出现在 Dock 中,并且可能不会创建窗口或被激活。
¥'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated.
app.importCertificate(options, callback)
Linux
-
callback
函数¥
callback
Function-
result
整数 - 导入结果。¥
result
Integer - Result of import.
-
将 pkcs12 格式的证书导入到平台证书存储中。callback
与导入操作的 result
一起调用,根据 Chromium net_error_list,值 0
表示成功,任何其他值表示失败。
¥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 提供商支持它,则
¥DNS-over-HTTPS, if the DNS provider supports it, then
-
内置解析器(默认情况下仅在 macOS 上启用),然后
¥the built-in resolver (enabled on macOS only by default), then
-
系统的解析器(例如
getaddrinfo
)。¥the system's resolver (e.g.
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'
]
})
})
必须在 ready
事件发出后调用此 API。
¥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.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 processes 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
事件发出后可用。
¥Note: This information is only usable after the gpu-info-update
event is emitted.
app.getGPUInfo(infoType)
-
infoType
字符串 - 可以是basic
或complete
。¥
infoType
string - Can bebasic
orcomplete
.
返回 Promise<unknown>
¥Returns Promise<unknown>
对于 infoType
等于 complete
:Object
包含了 chromium 的 GPUInfo 对象 中的所有 GPU 信息,从而实现了 promise。这包括 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
:与 complete
所请求的相比,使用 Object
包含更少的属性来履行 promise。这是基本响应的示例:
¥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.
app.setBadgeCount([count])
Linux macOS
-
count
整数(可选) - 如果提供了值,请将徽章设置为提供的值,否则,在 macOS 上,显示纯白点(例如未知数量的通知)。在 Linux 上,如果未提供值,则不会显示徽章。¥
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). On Linux, if a value is not provided the badge will not display.
返回 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 集成文档。
¥Note: Unity launcher requires a .desktop
file to work. For more information,
please read the Unity integration documentation.
注意:在 macOS 上,你需要确保你的应用有权显示通知,此方法才能发挥作用。
¥Note: On macOS, you need to ensure that your application has the permission to display notifications for this method to work.
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
(如果应用设置为在登录时打开)。¥
openAtLogin
boolean -true
if the app is set to open at login. -
openAsHidden
布尔值 macOS 已弃用 -true
(如果应用设置为在登录时隐藏打开)。这不适用于 macOS 13 及更高版本。¥
openAsHidden
boolean macOS Deprecated -true
if the app is set to open as hidden at login. This does not work on macOS 13 and up. -
wasOpenedAtLogin
布尔值 macOS -true
(如果应用在登录时自动打开)。¥
wasOpenedAtLogin
boolean macOS -true
if the app was opened at login automatically. -
wasOpenedAsHidden
布尔值 macOS 已弃用 -true
(如果应用作为隐藏登录项打开)。这表明应用不应在启动时打开任何窗口。此设置在 MAS 构建 或 macOS 13 及更高版本上不可用。¥
wasOpenedAsHidden
boolean macOS Deprecated -true
if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on MAS builds or on macOS 13 and up. -
restoreState
布尔值 macOS 已弃用 -true
如果应用作为登录项打开,则应恢复上一个会话的状态。这表示应用应恢复上次关闭应用时打开的窗口。此设置在 MAS 构建 或 macOS 13 及更高版本上不可用。¥
restoreState
boolean macOS Deprecated -true
if the app was opened as a login item that should restore the state from the previous session. 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 or on macOS 13 and up. -
status
字符串 macOS - 可以是not-registered
、enabled
、requires-approval
或not-found
之一。¥
status
string macOS - can be one ofnot-registered
,enabled
,requires-approval
, ornot-found
. -
executableWillLaunchAtLogin
布尔 Windows -true
如果应用设置为在登录时打开并且其运行键未停用。这与openAtLogin
不同,因为它忽略args
选项,如果在登录时使用任何参数启动给定的可执行文件,则此属性将为 true。¥
executableWillLaunchAtLogin
boolean Windows -true
if app is set to open at login and its run key is not deactivated. This differs fromopenAtLogin
as it ignores theargs
option, this property will be true if the given executable would be launched at login with any arguments. -
launchItems
对象[]窗口¥
launchItems
Object[] Windows-
name
字符串 Windows - 注册表项的名称值。¥
name
string Windows - name value of a registry entry. -
path
字符串 Windows - 与注册表项对应的应用的可执行文件。¥
path
string Windows - The executable to an app that corresponds to a registry entry. -
args
字符串[] Windows - 要传递给可执行文件的命令行参数。¥
args
string[] Windows - the command-line arguments to pass to the executable. -
scope
字符串 Windows -user
或machine
之一。指示注册表项是在HKEY_CURRENT USER
还是HKEY_LOCAL_MACHINE
下。¥
scope
string Windows - one ofuser
ormachine
. Indicates whether the registry entry is underHKEY_CURRENT USER
orHKEY_LOCAL_MACHINE
. -
enabled
布尔 Windows -true
(如果应用注册表项已批准启动),因此在任务管理器和 Windows 设置中显示为enabled
。¥
enabled
boolean Windows -true
if the app registry key is startup approved and therefore shows asenabled
in Task Manager and Windows settings.
-
app.setLoginItemSettings(settings)
macOS Windows
-
settings
对象¥
settings
Object-
openAtLogin
布尔值(可选) -true
在登录时打开应用,false
将应用作为登录项删除。默认为false
。¥
openAtLogin
boolean (optional) -true
to open the app at login,false
to remove the app as a login item. Defaults tofalse
. -
openAsHidden
布尔值(可选) macOS 已弃用 -true
将应用打开为隐藏。默认为false
。用户可以从系统偏好设置中编辑此设置,因此在打开应用时应检查app.getLoginItemSettings().wasOpenedAsHidden
以了解当前值。此设置在 MAS 构建 或 macOS 13 及更高版本上不可用。¥
openAsHidden
boolean (optional) macOS Deprecated -true
to open the app as hidden. Defaults tofalse
. The user can edit this setting from the System Preferences soapp.getLoginItemSettings().wasOpenedAsHidden
should be checked when the app is opened to know the current value. This setting is not available on MAS builds or on macOS 13 and up. -
type
字符串(可选)macOS - 添加为登录项的服务类型。默认为mainAppService
。仅适用于 macOS 13 及更高版本。¥
type
string (optional) macOS - The type of service to add as a login item. Defaults tomainAppService
. Only available on macOS 13 and up.-
mainAppService
- 主要应用。¥
mainAppService
- The primary application. -
agentService
- 启动代理的属性列表名称。属性列表名称必须与应用的Contents/Library/LaunchAgents
目录中的属性列表相对应。¥
agentService
- The property list name for a launch agent. The property list name must correspond to a property list in the app’sContents/Library/LaunchAgents
directory. -
daemonService
字符串(可选)macOS - 启动代理的属性列表名称。属性列表名称必须与应用的Contents/Library/LaunchDaemons
目录中的属性列表相对应。¥
daemonService
string (optional) macOS - The property list name for a launch agent. The property list name must correspond to a property list in the app’sContents/Library/LaunchDaemons
directory. -
loginItemService
字符串(可选)macOS - 登录项服务的属性列表名称。属性列表名称必须与应用的Contents/Library/LoginItems
目录中的属性列表相对应。¥
loginItemService
string (optional) macOS - The property list name for a login item service. The property list name must correspond to a property list in the app’sContents/Library/LoginItems
directory.
-
-
serviceName
字符串(可选)macOS - 服务的名称。如果type
非默认,则为必需。仅适用于 macOS 13 及更高版本。¥
serviceName
string (optional) macOS - The name of the service. Required iftype
is non-default. Only available on macOS 13 and up. -
path
字符串(可选) Windows - 登录时启动的可执行文件。默认为process.execPath
。¥
path
string (optional) Windows - The executable to launch at login. Defaults toprocess.execPath
. -
args
字符串[](可选)Windows - 要传递给可执行文件的命令行参数。默认为空数组。请注意将路径用引号引起来。¥
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
布尔值(可选) Windows -true
将更改启动批准的注册表项,enable / disable
将更改任务管理器和 Windows 设置中的应用。默认为true
。¥
enabled
boolean (optional) Windows -true
will change the startup approved registry key andenable / disable
the App in Task Manager and Windows Settings. Defaults totrue
. -
name
字符串(可选) Windows - 要写入注册表的值名称。默认为应用的 AppUserModelId()。¥
name
string (optional) Windows - value name to write into registry. Defaults to the app's AppUserModelId().
-
设置应用的登录项设置。
¥Set the app's login item settings.
要在 Windows 上使用 Electron 的 autoUpdater
(它使用 Squirrel),你需要将启动路径设置为 Update.exe,并传递指定应用名称的参数。例如:
¥To work with Electron's 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. For example:
const { app } = require('electron')
const path = require('node:path')
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"'
]
})
有关在 macOS 13 及更高版本上将不同服务设置为登录项的更多信息,请参阅 SMAppService
。
¥For more information about setting different services as login items on macOS 13 and up, see SMAppService
.
app.isAccessibilitySupportEnabled()
macOS Windows
返回 boolean
- 如果启用了 Chrome 的辅助功能支持,则为 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
布尔值 - 启用或禁用 可达性树 渲染¥
enabled
boolean - Enable or disable accessibility tree rendering
手动启用 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.
必须在 ready
事件发出后调用此 API。
¥This API must be called after the ready
event is emitted.
注意:渲染辅助功能树可以显着影响应用的性能。默认情况下不应启用它。
¥Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
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 documentation。
¥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 编码的安全范围书签数据。¥
bookmarkData
string - The base64 encoded security scoped bookmark data returned by thedialog.showOpenDialog
ordialog.showSaveDialog
methods.
返回 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 应用可以到达其沙箱之外,以访问用户选择的文件。有关该系统如何工作的说明,请参阅 苹果的文档。
¥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。如果我们无法执行复制,那么此方法将抛出错误。错误中的消息应该提供丰富的信息,并准确地告诉你出了什么问题。
¥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. 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.
默认情况下,如果应用目录中存在与要移动的应用同名的应用并且未运行,则现有应用将被丢弃,活动应用将移至其位置。如果它正在运行,先前存在的正在运行的应用将获得焦点,并且先前活动的应用将自行退出。可以通过提供可选的冲突处理程序来更改此行为,其中处理程序返回的布尔值确定是否使用默认行为解决移动冲突。即返回 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
¥
enabled
boolean - Enable or disableSecure 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.
详细信息请参见 苹果的文档。
¥See Apple's documentation for more details.
注意:仅在需要时启用 Secure Keyboard Entry
,不再需要时禁用它。
¥Note: Enable Secure Keyboard Entry
only when it is needed and disable it when it is no longer needed.
app.setProxy(config)
config
ProxyConfig
返回 Promise<void>
- 代理设置过程完成后即可解决。
¥Returns Promise<void>
- Resolves when the proxy setting process is complete.
为没有关联 会议 的网络请求设置代理设置。目前,这将影响 实用进程 中使用 网 发出的请求以及运行时发出的内部请求(例如:地理位置查询)。
¥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
URL
返回 Promise<string>
- 使用 url
的代理信息进行解析,该信息将在尝试使用 实用进程 中的 网 发出请求时使用。
¥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.
属性
¥Properties
app.accessibilitySupportEnabled
macOS Windows
如果启用了 Chrome 的辅助功能支持,则 boolean
属性为 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.
必须在 ready
事件发出后调用此 API。
¥This API must be called after the ready
event is emitted.
注意:渲染辅助功能树可以显着影响应用的性能。默认情况下不应启用它。
¥Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
app.applicationMenu
一个 Menu | null
属性,如果已设置,则返回 Menu
,否则返回 null
。用户可以通过 Menu 来设置该属性。
¥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 集成文档。
¥Note: Unity launcher requires a .desktop
file to work. For more information,
please read the Unity integration documentation.
注意:在 macOS 上,你需要确保你的应用有权显示通知,此属性才能生效。
¥Note: On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect.
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 中的应用图标执行操作。
¥A Dock
| undefined
object that allows you to perform actions on your app icon in the user's
dock on macOS.
app.isPackaged
只读
¥app.isPackaged
Readonly
如果应用已打包,则返回 true
的 boolean
属性,否则返回 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.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.
根据 npm 模块规范,通常 package.json
的 name
字段是一个短的小写名称。你通常还应该指定 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 翻译环境 或 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.