app
控制应用程序的事件生命周期。
ProcessMain
下面的这个例子将会展示如何在最后一个窗口被关闭时退出应用:
const { app } = require('electron')
app.on('window-all-closed', () => {
app.quit()
})
事件
app 对象会发出以下事件:
事件: 'will-finish-launching'
当应用程序完成基础的启动的时候被触发。在 Windows 和 Linux 中, will-finish-launching 事件与 ready 事件是相同的; 在 macOS 中,这个事件相当于 NSApplication 中的 applicationWillFinishLaunching 提示。
绝大部分情况下,你必须在ready事件句柄中处理所有事务。
事件: 'ready'
返回:
eventEventlaunchInfoRecord<string, any> | NotificationResponse macOS
当 Electron 完成初始化时,发出一次。在 macOS 上,如果通过通知中心启动应用程序,launchInfo 保存 NSUserNotification 的 userInfo 或 UNNotificationResponse 的信息。你也可以通过调用 app.isReady() 来检查该事件是否已被触发,以及通过 app.whenReady() 得到一个当Electron已初始化后fulfill 的 Promise。
[!NOTE] The
readyevent 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 thereadyevent, ensure that it is called synchronously in the top-level context of the main process.
事件: 'window-all-closed'
当所有的窗口都被关闭时触发。
如果你没有监听此事件并且所有窗口都关闭了,默认的行为是控制退出程序;但如果你监听了此事件,你可以控制是否退出程序。如果用户按下了 Cmd + Q,或者开发者调用了 app.quit(),Electron 会首先关闭所有的窗口然后触发 will-quit 事件,在这种情况下 window-all-closed 事件不会被触发。
事件:'before-quit'
返回:
eventEvent
在程序关闭窗口前发信号。调用 event.preventDefault() 将阻止终止应用程序的默认行为。
[!NOTE] If application quit was initiated by
autoUpdater.quitAndInstall(), thenbefore-quitis emitted after emittingcloseevent on all windows and closing them.
[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。
事件: 'will-quit'
返回:
eventEvent
当所有窗口被关闭后触发,同时应用程序将退出。调用 event.preventDefault() 将阻止终止应用程序的默认行为。
关于 window-all-closed 和 will-quit 事件之间的差异, 请参见 window-all-closed 事件的说明。
[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。
事件: 'quit'
返回:
eventEventexitCodeInteger
在应用程序退出时发出。
[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。
事件: 'open-file' macOS
返回:
eventEventpathstring
当用户想要在应用中打开一个文件时发出。 open-file 事件通常在应用已经打开,并且系统要再次使用该应用打开文件时发出。 open-file也会在一个文件被拖到 dock 并且还没有运行的时候发出。请确认在应用启动的时候(甚至在 ready 事件发出前) 就对 open-file 事件进行监听。
如果你想处理这个事件,你应该调用 event.preventDefault() 。
在 Windows 系统中,你需要解析 process.argv (在主进程中) 来获取文件路径
事件: 'open-url' macOS
返回:
eventEventurlstring
当用户想要在应用中打开一个 URL 时发出。你的应用程序的 Info. plist 文件必须在 CFBundleURLTypes 这个key中定义 url scheme, 并将 NSPrincipalClass 设置为 AtomApplication。
与 open-file 事件一样,请务必在应用程序启动时尽早注册 open-url 事件的侦听器,以检测应用程序是否正在被某个 URL 打开。如果在 ready 事件回调中注册侦听器,您将错过触发应用程序启动的 URL 。
事件: 'activate' macOS
返回:
eventEventhasVisibleWindowsboolean
当应用被激活时发出。各种操作都可以触发此事件, 例如首次启动应用程序、尝试在应用程序已运行时或单击应用程序的坞站或任务栏图标时重新激活它。
Event: 'app-shim-connected' macOS Experimental
返回:
eventEventshimAppShimHost
Emitted when an app shim connects to your app. Shims can only connect after app.startAppShimServer() has been called.
Any process running as the same user can connect. Verify the shim before creating windows in it, for example with shim.satisfiesCodeRequirement(), and call shim.quit() to reject a shim that you do not trust.
Event: 'app-shim-version-mismatch' macOS Experimental
返回:
eventEventbundlePathstring - The path of the app shim's bundle.
Emitted when an app shim was launched but could not connect because your app's bundle has been replaced by a different version since your app started. A shim loads the version of Electron that is on disk, which cannot communicate with the version that is still running.
The shim quits without showing any UI, so use this event to tell the user what happened. Shims can connect again after your app restarts.
const { app, dialog } = require('electron')
app.on('app-shim-version-mismatch', async () => {
const { response } = await dialog.showMessageBox({
message: `Restart ${app.name} to finish updating`,
buttons: ['Restart', 'Later']
})
if (response === 0) {
app.relaunch()
app.quit()
}
})
事件: 'did-become-active' macOS
返回:
eventEvent
当应用即将被激活时触发。不同于 activate 事件,did-become-active 事件将在每次程序被激活前都触发,而不仅仅是 Dock 图标被点击或者应用重启。当用户通过 macOS 应用切换器切换到程序时也会被触发。
事件: 'did-rele-active' macOS
返回:
eventEvent
当程序长时间处于非激活(Active)、非聚焦(focus)状态时触发。例如:点击其他应用,或者通过应用切换器切换到其他应用时,就会被触发。
Event: 'continue-activity' macOS
返回:
eventEventtypestring-标识活动的字符串。 Maps toNSUserActivity.activityType.userInfounknown - 包含另一个设备上activity存储的应用特定状态。detailsObjectwebpageURLstring (可选) - 如果可用,可识别另一设备上活动访问的网页的 URL 的字符串。
在 Handoff 期间,当来自其他设备的活动需要恢复时,也会触发。如果你想处理这个事件,你应该调用 event.preventDefault() 。
只有具有支持相应的活动类型并且相同的开发团队 ID 作为启动程序时,用户行为才会进行。所支持活动类型已在应用的 Info.plist 中的 NSUserActivityTypes 里明确定义。
Event: 'will-continue-activity' macOS
返回:
eventEventtypestring-标识活动的字符串。 Maps toNSUserActivity.activityType.
在 Handoff 期间,当来自其他设备的活动需要恢复前触发。如果你想处理这个事件,你应该调用 event.preventDefault() 。
Event: 'continue-activity-error' macOS
返回:
eventEventtypestring-标识活动的字符串。 Maps toNSUserActivity.activityType.errorstring - 详细的错误信息
在 Handoff 期间,当来自其他设备的活动恢复失败时触发。
Event: 'activity-was-continued' macOS
返回:
eventEventtypestring-标识活动的字符串。 Maps toNSUserActivity.activityType.userInfounknown - 包含activity存储的应用特定状态。
在 Handoff 期间,当来自此设备的活动在其他设备恢复时触发。
Event: 'update-activity-state' macOS
返回:
eventEventtypestring-标识活动的字符串。 Maps toNSUserActivity.activityType.userInfounknown - 包含activity存储的应用特定状态。
在 Handoff 期间,当来自此设备的活动在其他设备即将恢复时触发。如果需要更新要传输的状态,你应该立即调用 event.preventDefault(), 构造新的 userInfo 字典,并及时调用 app.updateCurrentActiviy()。否则,操作会失败,并且触发 continue-activity-error
事件: 'new-window-for-tab' macOS
返回:
eventEvent
当用户点击原生的macOS新标签按钮时触发。 The new tab button is only visible if the current BrowserWindow has a tabbingIdentifier.
You must create a window in this handler in order for macOS tabbing to work as expected.
事件: 'browser-window-blur'
返回:
eventEventwindowBrowserWindow
当 browserWindow 失去焦点时触发。
事件: 'browser-window-focus'
返回:
eventEventwindowBrowserWindow
当 browserWindow 获得焦点时触发。
事件: 'browser-window-created'
返回:
eventEventwindowBrowserWindow
当一个新的 browserWindow 被创建时触发。
事件: 'web-contents-created'
返回:
eventEventwebContentsWebContents
当一个新的 webContents 被创建时触发。
事件: 'certificate-error'
返回:
eventEventwebContentsWebContentsurlstringerrorstring - 错误码certificateCertificatecallbackFunctionisTrustedboolean - 是否将证书视为受信任。
isMainFrameboolean
当对 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)
}
})
事件: 'select-client-certificate'
返回:
eventEventwebContentsWebContents | nullurlURLcertificateListCertificate[]callbackFunctioncertificateCertificate(证书) (可选)
当一个客户证书被请求的时候发出。
url 指的是请求客户端认证的网页地址,调用 callback 时需要传入一个证书列表中的证书。需要通过调用 event.preventDefault() 来防止应用自动使用第一个证书进行验证。
webContents is null when the request does not originate from a renderer process, for example when using net.request or net.fetch in the main process, or from a utility process created with respondToAuthRequestsFromMainProcess: true. For utility processes created without that flag, net requests proceed without a client certificate and this event is not emitted.
const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})
事件: "login"
返回:
eventEventwebContentsWebContents | nullauthenticationResponseDetailsObjecturlURLpidnumberisRequestForNavigationboolean - Indicates whether the request is for a navigation.firstAuthAttemptboolean - Indicates whether this is the first authentication attempt.responseHeadersRecord<string, string | string[]> (optional) - The headers returned in the response.
authInfoObjectisProxybooleanschemestringhoststringportIntegerrealmstring
callbackFunctionusernamestring (可选)passwordstring (可选)
当 webContents 或者 Utility 进程 想要进行基础验证时触发。
默认行为是取消所有身份验证。默认行为是取消所有的验证行为,如果需要重写这个行为,你需要用 event.preventDefault() 来阻止默认行为,并且使用 callback(username, password) 来验证。
const { app } = require('electron')
app.on('login', (event, webContents, details, authInfo, callback) => {
event.preventDefault()
callback('username', 'secret')
})
当 callback 在缺少用户名和密码的时候被调用,身份验证请求将被取消,同时将返回身份验证错误到页面。
事件: 'gpu-info-update'
每当有 GPU 信息更新时触发。
事件: 'render-process-gone'
返回:
eventEventwebContentsWebContentsdetailsRenderProcessGoneDetails
渲染器进程意外消失时触发。这种情况通常因为进程崩溃或被杀死。
事件: 'child-process-gone'
返回:
eventEventdetailsObjecttypestring - 进程类型。以下值之一:UtilityZygoteSandbox helperGPUPepper PluginPepper Plugin BrokerUnknown
reasonstring - 子进程结束的原因。可选值:clean-exit- 以零为退出代码退出的进程abnormal-exit- 以非零退出代码退出的进程killed- 进程发送一个SIGTERM,否则是被外部杀死的。crashed- 进程崩溃oom- 进程内存不足launch-failed- 进程从未成功启动integrity-failure- 窗口代码完整性检查失败memory-eviction- Process proactively terminated to prevent a future out-of-memory (OOM) situation
exitCodenumber - The exit code for the process (e.g. status from waitpid if on POSIX, from GetExitCodeProcess on Windows), unlessreasonislaunch-failed, in which caseexitCodewill be a platform-specific launch failure error code.systemErrorCodenumber (optional) Windows - The Windows system error code (GetLastError()) of the failed launch. Only set whenreasonislaunch-failed.serviceNamestring (可选) - 进程的非本地化名称。namestring (可选) - 进程的名称。功能性示例:Audio Service,Content Decryption Module Service,Network Service,Video Capture, 等等。
子进程意外消失时触发。 This is normally because it was crashed or killed, or because it failed to launch. It does not include renderer processes.
事件: "accessibility-support-changed" _ macOS _ _ Windows _
返回:
eventEventaccessibilitySupportEnabledboolean -truewhen Chromium's accessibility support is enabled,falseotherwise.
Emitted when Chromium's accessibility support changes. 当启用或禁用辅助技术时将触发此事件,例如屏幕阅读器 。查看更多详情 https://www.chromium.org/developers/design-documents/accessibility
事件:'session-created'
返回:
sessionSession
当 Electron创建了一个新的 session后被触发.
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
事件: 'second-instance'
返回:
eventEventargvstring[] - 第二实例命令行参数的数组。workingDirectorystring - 第二实例的工作目录。additionalDataunknown - 第二个实例发送过来的额外的 JSON 对象
当第二个实例被执行并且调用 app.requestSingleInstanceLock() 时,这个事件将在你的应用程序的首个实例中触发 An instance is considered a second instance if it shares the same user data directory (app.getPath('userData')) as the primary instance (and on Windows, the same executable name).
argv 是第二个实例的命令行参数的数组, workingDirectory 是这个实例当前工作目录。通常, 应用程序会激活窗口并且取消最小化来响应。
argv will not be exactly the same list of arguments as those passed to the second instance. 顺序可能会发生变化,并且可能会追加额外的参数。如果需要保持完全相同的参数,建议改用 additionalData 。
[!NOTE] If the second instance is started by a different user than the first, the
argvarray will not include the arguments.
保证在 app 的 ready 事件发出后发出此事件。
[!NOTE] Extra command line arguments might be added by Chromium, such as
--original-process-start-time.
方法
app 对象具有以下方法:
[!NOTE] Some methods are only available on specific operating systems and are labeled as such.
app.quit()
尝试关闭所有窗口将首先发出 before-quit 事件。如果所有窗口都已成功关闭, 则将发出 will-quit 事件, 并且默认情况下应用程序将终止。
此方法会确保执行所有beforeunload 和 unload事件处理程序。可以在退出窗口之前的beforeunload事件处理程序中返回false取消退出。
app.exit([exitCode])
exitCodeInteger (可选)
使用 exitCode 立即退出。 exitCode 默认为0。
所有窗口都将立即被关闭,而不询问用户,而且 before-quit 和 will-quit 事件也不会被触发。
app.relaunch([options])
在当前实例退出时重新启动应用程序。
默认情况下,新实例将使用与当前实例相同的工作目录和命令行参数。当指定了 args 时,args 将作为命令行参数传递。当指定了 execPath 时,execPath 将被执行以重新启动,而不是当前应用程序。
请注意,此方法在执行时并不会退出应用程序。在调用 app.relaunch 后,必须调用 app.quit 或 app.exit 才能使应用程序重新启动。
当多次调用 app.relaunch 时,当前实例退出后将启动多个实例。
一个立即重启当前实例并向新实例添加命令行参数的示例:
const { app } = require('electron')
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0)
app.isReady()
如果 Electron 已完成初始化返回 boolean - true,否则 false 。另见 app.whenReady()。
app.whenReady()
返回 Promise<void> - 当Electron 初始化完成。可用作检查 app.isReady() 的方便选择,假如应用程序尚未就绪,则订阅ready事件。
app.focus([options])
On macOS, makes the application the active app. On Windows, focuses on the application's first window. On Linux, either focuses on the first visible window (X11) or requests focus but may instead show a notification or flash the app icon (Wayland).
你应该尽可能少地使用 steal 选项。
app.isActive() macOS
Returns boolean - true if the application is active (i.e. focused).
app.hide() macOS
隐藏所有的应用窗口,不是最小化.
app.isHidden() macOS
返回 boolean - 如果应用的所有窗口都被隐藏(比如在 MacOS 系统下使用了 Command-H 快捷键)则为 true ,否则返回 false。
app.show() macOS
显示隐藏后的应用程序窗口。不会使它们自动获得焦点。
app.setAppLogsPath([path])
pathstring (可选) - 自定义日志路径。必须是绝对路径。
设置或创建一个您的应用程序日志目录,然后可以通过 app.getPath() 或 app.setPath(pathName, newPath) 进行操作。
调用 app.setAppLogsPath() 却没有指定 path 参数将导致此目录在 macOS 下被设置为 ~/Library/Logs/YourAppName;在 Linux 和_Windows_ 下将被设置到 userData 目录中。
app.getAppPath()
返回 string - 当前应用程序目录。
app.getPath(name)
namestring - 您可以通过名称请求以下路径:home用户的 home 文件夹(主目录)appData每个用户的应用程序数据目录,默认情况下指向:%APPDATA%Windows 中$XDG_CONFIG_HOMEor~/.configLinux 中~/Library/Application SupportmacOS 中
assetsThe directory where app assets such asresources.pakare stored. By default this is the same as the folder containing theexepath. Available on Windows and Linux only.userData储存你应用程序配置文件的文件夹,默认是appData文件夹附加应用的名称 On Windows, the app's name must not contain reserved filename characters. 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. It is recommended to store app-specific files within a subdirectory ofuserData(e.g.,path.join(app.getPath('userData'), 'my-app-data')) rather than directly inuserDataitself, to avoid naming conflicts with Chromium's own subdirectories (such asCache,GPUCache, andLocal Storage).sessionDataThe directory for storing data generated bySession, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, DevTools files and compiled GPU shaders. By default this points touserData. Chromium 可能在此处写入非常大的磁盘缓存,因此,如果您的应用不依赖于浏览器存储(如 localStorage 或 cookie)来保存用户数据,建议将此目录设置为其他位置,以避免污染userData目录。temp临时文件夹exe当前的可执行文件moduleThe location of the Chromium module. By default this is synonymous withexe.desktop当前用户的桌面文件夹documents用户文档目录的路径downloads用户下载目录的路径music用户音乐目录的路径pictures用户图片目录的路径videos用户视频目录的路径recent用户最近文件的目录 (仅限 Windows)。logs应用程序的日志文件夹crashDumps崩溃转储文件存储的目录。 See Crash Reporting.
返回 string - 与 name 关联的目录或文件的路径。失败会抛出一个Error。
If app.getPath('logs') is called without calling app.setAppLogsPath() being called first, a default log directory will be created equivalent to calling app.setAppLogsPath() without a path parameter.
app.getFileIcon(path[, options])
pathstring
返回 Promise<NativeImage> - 使用应用程序的图标(即 NativeImage 类型)来完成。
读取文件的关联图标。
On Windows, there are 2 kinds of icons:
- 与某些文件扩展名相关联的图标, 比如
. mp3,. png等。 - 文件本身就带图标,像是
.exe,.dll,.ico
在 Linux 和 macOS 上,图标依赖于与应用程序关联的文件 mime 类型。
app.setPath(name, path)
namestringpathstring
重写 name 的路径为 path,一个特定的文件夹或者文件。如果路径指向一个不存在的目录,则抛出一个 Error。在这种情况下,目录应该以 fs.mkdirSync 或类似的方式创建。
name 参数只能使用 app.getPath 定义过的 name
默认, 网页的 cookies 和 缓存 将存储在 sessionData 目录下。如果要更改此位置,你必须在 app 模块的 ready 事件之前重写 sessionData 路径。
app.getVersion()
返回 string - 加载应用程序的版本号。如果应用程序的 package. json 文件中找不到版本号, 则返回当前包或者可执行文件的版本。
app.getName()
返回 string - 当前应用程序的名称,即为该应用程序 package.json 文件的 name 字段。
根据 npm 的命名规则, 通常 package.json 中的 name 字段是一个短的小写字符串。通常还应该指定一个 productName 字段, 是首字母大写的完整名称,用于表示应用程序的名称。Electron 会优先使用这个字段作为应用名。
Electron uses the application's name to construct the default userData directory. On Windows, neither productName nor name should contain the following special characters, which cannot be used in directory or file names: <, >, :, ", \, /, |, ?, *. Using these characters in the application's name can prevent Electron from creating the default userData directory and cause the application to crash on startup.
app.setName(name)
namestring
设置当前应用程序的名字
On Windows, avoid the reserved filename characters in name.
[!NOTE] This function overrides the name used internally by Electron; it does not affect the name that the OS uses.
app.setDesktopName(name) Linux
namestring - The.desktopfilename (e.g.'com.example.MyApp.desktop').
Sets the .desktop filename on Linux. This must match the base filename of the app's installed .desktop file. The .desktop suffix is optional.
The name (without the .desktop suffix) is the app's identity for Linux desktop integration. It should be a reverse-DNS style ID such as com.example.MyApp, following the desktop entry naming conventions. This value is used as:
- the XDG application ID (
app_id) on Wayland andWM_CLASSon X11, used to match the app's icon and window grouping. - the app ID that
xdg-desktop-portalreports to portal backends such as GlobalShortcuts.
Portals increasingly enforce this identity. If the name is not a valid reverse-DNS ID or does not match an installed .desktop file:
- GNOME 50.0/50.1 (Ubuntu 26.04) rejects
globalShortcutbinds withorg.freedesktop.portal.Error.NotAllowed— with no error surfaced to the app (see #52218). xdg-desktop-portal1.21 and later refuses portal sessions for app IDs it cannot resolve to a.desktopfile.
If this value is not set and desktopName is not present in package.json, Electron falls back to a lowercased, hyphenated slug of the app's name (e.g. My App → my-app.desktop), which is unlikely to be a valid portal identity — packaged apps should always set it explicitly.
This API must be called before the ready event. The value can also be set using desktopName in package.json.
app.getLocale()
返回 string - 当前应用程序区域,使用 Chromium's l10n_util 库获取。 Possible return values are documented here.
要设置语言区域,您需要在应用启动时使用命令行开关,相关内容可以在这里找到。
[!NOTE] When distributing your packaged app, you have to also ship the
localesfolder.
[!NOTE] This API must be called after the
readyevent is emitted.
[!NOTE] To see example return values of this API compared to other locale and language APIs, see
app.getPreferredSystemLanguages().
app.getLocaleCountryCode()
Returns string - User operating system's locale two-letter ISO 3166 country code. 该值取自本地操作系统 API。
[!NOTE] When unable to detect locale country code, it returns empty string.
app.getSystemLocale()
返回 string - 当前系统区域。在 Windows 和 Linux,使用 Chromium's i18n 库来获取。在 macOS 上,改为使用 [NSLocale currentLocale]。为了获得用户当前的系统语言(这种语言并不总是与本地语言相同),最好使用 app.getPreferredSystemLanguages()。
不同的操作系统也以不同的方式使用区域数据:
- Windows 11 使用数字、日期和时间的区域格式。
- macOS Monterey 使用该区域来格式化数字、日期、时间以及选择要使用的货币符号。
因此,此 API 可用于选择用于在日历应用中呈现日期和时间的格式等目的,尤其是当开发人员希望格式与操作系统一致时。
[!NOTE] This API must be called after the
readyevent is emitted.
[!NOTE] To see example return values of this API compared to other locale and language APIs, see
app.getPreferredSystemLanguages().
app.getPreferredSystemLanguages()
返回 string[] - 从最喜欢到最不喜欢的用户首选系统语言,包括国家代码(如果适用)。用户可以在 Windows 或 macOS 上通过语言和区域设置、修改、添加此列表。
API 在 Windows 上使用 GlobalizationPreferences(回退到 GetSystemPreferredUILanguages),在 macOS 上使用 \[NSLocale preferredLanguages\],在 Linux 上使用 g_get_language_names。
此 API 可用于决定以何种语言呈现应用程序。
以下是具有不同配置的各种语言和语言环境 API 的返回值的一些示例:
对于 Windows,应用程序区域设置为德语,区域格式为芬兰语(芬兰),首选系统语言从高到低依次为法语(加拿大)、英语(美国)、简体中文(中国)、芬兰语和西班牙语 (拉丁美洲):
app.getLocale() // 'de'
app.getSystemLocale() // 'fi-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']
在 macOS 上,应用程序区域设置为德语,区域为芬兰,首选系统语言从高到低依次为法语(加拿大)、英语(美国)、简体中文和西班牙语(拉丁美洲):
app.getLocale() // 'de'
app.getSystemLocale() // 'fr-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']
两种操作系统的可用语言和地区以及可能的返回值都不同。
从上面的示例可以看出,在 Windows 上,首选系统语言可能没有国家代码,并且首选系统语言之一与用于区域格式的语言相对应。 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
pathstring
将此 path 添加到最近打开的文件列表中
此列表由操作系统管理。在Windows上,您可以从任务栏访问此列表,在macOS上,您可以从dock菜单访问。
app.clearRecentDocuments() macOS Windows
清空最近打开的文档列表
app.getRecentDocuments() macOS Windows
Returns string[] - An array containing documents in the most recent documents list.
const { app } = require('electron')
const path = require('node:path')
const file = path.join(app.getPath('desktop'), 'foo.txt')
app.addRecentDocument(file)
const recents = app.getRecentDocuments()
console.log(recents) // ['/path/to/desktop/foo.txt'}
app.setAsDefaultProtocolClient(protocol[, path, args])
protocolstring - 协议的名称,不带://。例如,如果你希望应用处理electron://链接,请以electron为参数调用此方法。pathstring (可选) Windows - Electron可执行文件路径。默认为process.execPathargsstring[] (可选) Windows - 传递给可执行文件的参数。默认为空数组。
返回 boolean - 是否调用成功。
将当前可执行文件的设置为协议(也就是 URI scheme) 的默认处理程序。该方法允许你将应用更深入地集成到操作系统中。一旦注册了,所有 your-protocol:// 开头的链接将使用当前可执行文件打开。整个链接,包括协议部分,将作为参数传递给你的应用程序。
[!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 editinginfo.plistwith a text editor. Please refer to Apple's documentation for details.
[!NOTE] In a Windows Store environment (when packaged as an
appx) this API will returntruefor 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。
app.removeAsDefaultProtocolClient(protocol[, path, args]) macOS Windows
protocolstring - 协议的名称,不带://。pathstring (可选) _ Windows _-默认为process.execPathargsstring[] (可选) Windows - 默认为空数组
返回 boolean - 是否调用成功。
此方法检查当前可执行程序是否是协议(也就是URI scheme) 的默认处理程序。如果是,则会将应用移除默认处理器。
app.isDefaultProtocolClient(protocol[, path, args])
protocolstring - 协议的名称,不带://。pathstring (可选) _ Windows _-默认为process.execPathargsstring[] (可选) Windows - 默认为空数组
返回 boolean - 当前可执行程序是否是协议(也就是URI scheme) 的默认处理程序。
[!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.pliston the macOS machine. Please refer to Apple's documentation for details.
API 在内部使用 Windows 注册表和 LSCopyDefaultHandlerForURLScheme。
app.getApplicationNameForProtocol(url)
urlstring - 要检查的协议名称的 URL。不同于家族中的其他方法,该方法接收至少包含://(例如:https://)的完整URL。
返回 string - 处理协议的应用程序名称,或如果没有处理程序的空 字符串。例如,如果Electron 是这个URL的默认 处理程序,那么在 Windows 和 Mac 上,这个返回值可以是 Electron。然而,不要依赖于无法保证保持不变的精确格式。 Linux 上期望不同格式,可能带有 .desktop 后缀。
此方法返回URL协议(也就是URI scheme) 的默认处理器的应用程序名称。
app.getApplicationInfoForProtocol(url)
urlstring - 要检查的协议名称的 URL。不同于家族中的其他方法,该方法接收至少包含://(例如:https://)的完整URL。
返回 Promise<Object> - resolve包含以下内容的object:
iconNativeImage - 处理协议的应用程序的显示图标。pathstring - 处理协议的应用程序的安装路径。namestring - 处理协议的应用程序的显示名称。
此方法返回包含应用程序名称,图标和默认协议处理器路径(也就是URI scheme) 的Promise。
app.setUserTasks(tasks) Windows
tasksTask[] -Task的数组对象
Adds tasks to the Tasks category of the Jump List on Windows.
tasks 是一个 Task 的对象数组。
返回 boolean - 是否调用成功。
[!NOTE] If you'd like to customize the Jump List even more use
app.setJumpList(categories)instead.
app.getJumpListSettings() Windows
返回 Object:
minItemsInteger - 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).removedItemsJumpListItem[] - 与用户从跳转列表的自定义类别中明确移除的项目相对应的JumpListItem对象数组。这些项目不能在 next 调用app.setJumpList()时重新添加到跳转列表中, Windows不会显示任何包含已删除项目的自定义类别.
app.setJumpList(categories) Windows
categoriesJumpListCategory[] |null-JumpListCategory的对象数组。
Returns string
设置或删除应用程序的自定义跳转列表,并返回以下字符串之一:
ok- 没有出现错误error- 发生一个或多个错误,启用运行日志记录找出可能的原因。invalidSeparatorError- 已尝试在跳转列表中向自定义类别添加分隔符。分隔符只允许在标准Tasks类别下出现。fileTypeRegistrationError-尝试向自定义跳转列表添加一个文件链接,但是该应用未注册处理该应用类型customCategoryAccessDeniedError- 由于用户隐私或策略组设置,自定义类别无法添加到跳转列表。
如果 categories 的值为 null, 之前设定的自定义跳转列表(如果存在) 将被替换为标准的应用跳转列表(由windows生成)
[!NOTE] If a
JumpListCategoryobject has neither thetypenor thenameproperty set then itstypeis assumed to betasks. If thenameproperty is set but thetypeproperty is omitted then thetypeis assumed to becustom.
[!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 usingapp.getJumpListSettings().
[!NOTE] The maximum length of a Jump List item's
descriptionproperty is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed.
下面是创建自定义跳转列表的一个非常简单的示例:
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])
additionalDataRecord<any, any> (可选) - 一个包含要发送到第一个实例的附加数据的 JSON 对象。
返回 boolean
此方法的返回值表示你的应用程序实例是否成功取得了锁。如果它取得锁失败,你可以假设另一个应用实例已经取得了锁并且仍旧在运行,并立即退出。
即: 如果当前进程是应用程序的主要实例,则此方法返回true,同时你的应用会继续运行。如果当它返回 false如果你的程序没有取得锁,它应该立刻退出,并且将参数发送给那个已经取到锁的进程。
The single instance lock is scoped to the application's user data directory (app.getPath('userData')). Processes that share the same user data directory (and on Windows, the same executable name) will share the single instance lock. To run multiple independent instances of an application concurrently without triggering the single instance lock, set a different user data directory for each instance using app.setPath('userData', newPath) before calling app.requestSingleInstanceLock().
在 macOS 上, 当用户尝试在 Finder 中打开您的应用程序的第二个实例时, 系统会通过发出 open-file 和 open-url 事件来自动强制执行单个实例,。但是当用户在命令行中启动应用程序时, 系统的单实例机制将被绕过, 您必须手动调用此方法来确保单实例。
[!NOTE] On macOS and Linux, the second instance's command line arguments and
additionalDataare sent to the primary instance in a single message that is limited to 32 MB. Larger messages are dropped: this method still returnsfalse, but the primary instance does not emitsecond-instance.
在第二个实例启动时激活主实例窗口的示例:
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) => {
// 输出从第二个实例中接收到的数据
console.log(additionalData)
// 有人试图运行第二个实例,我们应该关注我们的窗口
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
app.whenReady().then(() => {
myWindow = new BrowserWindow({})
myWindow.loadURL('https://electronjs.org')
})
}
app.hasSingleInstanceLock()
返回 boolean
此方法返回你的应用实例当前是否持有单例锁。你可以通过 app.requestSingleInstanceLock()请求锁,并且通过 app.releaseSingleInstanceLock() 释放锁。
app.releaseSingleInstanceLock()
释放所有由 requestSingleInstanceLock 创建的锁。该方法将允许应用程序的多个实例再次并行运行。
app.setUserActivity(type, userInfo[, webpageURL]) macOS
typestring - 活动的唯一标识。 Maps toNSUserActivity.activityType.userInfoany - 存储供其他设备使用的特定应用状态。webpageURLstring (可选) - 如果在恢复的设备上没有安装合适的应用,则会在浏览器中加载的网页。协议必须是http或https。
创建一个 NSUserActivity 并将其设置为当前活动。 The activity is eligible for Handoff to another device afterward.
app.getCurrentActivityType() macOS
返回 string - 正在运行的 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
typestring - 活动的唯一标识。 Maps toNSUserActivity.activityType.userInfoany - 存储供其他设备使用的特定应用状态。
当其类型与 type 匹配时更新当前活动, 将项目从 用户信息 合并到其当前 用户信息 字典中。
app.setAppUserModelId(id) Windows
id字符串
Changes the Application User Model ID to id.
app.setToastActivatorCLSID(id) Windows
id字符串
Changes the Toast Activator CLSID to id. If one is not set via this method, it will be randomly generated for the app.
- The value must be a valid GUID/CLSID in one of the following forms:
- Canonical brace-wrapped:
{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}(preferred) - Canonical without braces:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(braces will be added automatically)
- Canonical brace-wrapped:
- Hex digits are case-insensitive.
This method should be called early (before showing notifications) so the value is baked into the registration/shortcut. Supplying an empty string or an unparsable value throws and leaves the existing (or generated) CLSID unchanged. If this method is never called, a random CLSID is generated once per run and exposed via app.toastActivatorCLSID.
app.setActivationPolicy(policy) macOS
policystring - 可以是'regular', 'accessory', 或 'prohibited'。
为给定应用设置激活策略。
激活策略类型:
- 'regulatory ' - 应用程序以普通应用出现在 Dock 中,可能有一个用户界面。
- 'accessory' - 应用程序不会出现在 Dock 中,没有菜单栏, 但它可能会被程序或在点击其某个窗口时激活。
- 'prohibited' - 应用程序不会出现在 Dock 中,可能无法创建窗口或被激活。
app.startAppShimServer([options]) macOS Experimental
Starts accepting connections from app shims. An app-shim-connected event is emitted for each shim that connects.
Throws if the server cannot be started, for example because another copy of your app has already started a server with the same name.
This method can only be called after the app is ready. It is not available in Mac App Store builds.
app.stopAppShimServer() macOS Experimental
Stops accepting connections from app shims. Shims that have already connected stay connected.
app.importCertificate(options, callback) Linux
选项对象certificatestring - pkcs12 文件的路径passwordstring - 证书的密码
callbackFunctionresultInteger - 导入结果
将 pkcs12 格式的证书导入到平台证书库。 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)
选项对象enableBuiltInResolverboolean (可选) - 当前内置主机解析器是否首选使用 getaddrinfo 。当启用时,内置解析器将尝试使用系统的DNS设置来进行DNS查询本身。 MacOS 默认开启,Windows 系统和 Linux 系统默认关闭enableHappyEyeballsboolean (optional) - Whether the Happy Eyeballs V3 algorithm should be used in creating network connections. When enabled, hostnames resolving to multiple IP addresses will be attempted in parallel to have a chance at establishing a connection more quickly.secureDnsModestring (可选) - 可选值: 'off', 'automatic' or 'secure'。配置 DNS-over-HTTP 模式。当设置为“off”时,将不会执行 DoH 查询。当设置为“automatic”时,如果 DoH 可用,将优先执行 DoH 查询;否则,将回退到不安全的 DNS 查询。当设置为“secure”时,将仅执行 DoH 查询。默认值: 'automatic'。secureDnsServersstring[] (可选) - 一个 DNS-over-HTTP 服务器模板列表。更多模板格式详见 RFC8484 § 3 。大多数服务器支持 POST 方法; 此类服务器的模板只需 URI 即可。需要注意的是 某些 DNS 提供商, 解析器将自动升级到 DoH 除非 DoH 明确禁用。DoH 服务提供列表为空也适用。enableAdditionalDnsQueryTypesboolean (可选) - 控制着是否添加额外的 DNS 查询类型,比如当通过不安全的 DNS 发出请求时,除传统的 A and AAAA 查询是否允许使用 HTTPS (DNS 类型 65) 。对安全的DNS没有任何效果,因为它总是允许附加类型。默认值为 true。
配置主机解析器 (DNS 和 DNS-over-HTTPS). 默认情况下,将使用下列解析器,按顺序排列:
- DNS-over-HTTPS, 如果 DNS 提供商可用
- 内置解析器 (默认 macOS 系统自动开启)
- 系统解析器 (比如
getaddrinfo).
这里可以配置为直接使用未加密 DNS (secureDnsMode: "secure"), 或者禁用 DNS-over-HTTPS (secureDnsMode: "off"). 也可以启用或禁用内置解析器
禁用安全 DNS 需要你指定 secureDnsMode 为 "secure". 如果你配置了, 你需要保证提供一个 DNS-over-HTTPS 服务器列表,防止用户的DNS配置没有提供DoH解析器支持.
const { app } = require('electron')
app.whenReady().then(() => {
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: ['https://cloudflare-dns.com/dns-query']
})
})
此 API 必须在 ready 事件触发后调用
app.configureWebAuthn(options) macOS
History
| Version(s) | Changes |
|---|---|
None | API ADDED |
选项对象touchIDObject (optional) - Enables the Touch ID / Secure Enclave platform authenticator for Web Authentication requests.keychainAccessGroupstring - The keychain access group that WebAuthn credentials will be stored under. This value must also be present in your app'skeychain-access-groupscode-signing entitlement, and is typically of the form<TEAM_ID>.<BUNDLE_ID>.webauthn.promptReasonstring (optional) - Customizes the reason text shown in the macOS Touch ID prompt. macOS renders the prompt as"<App Name>" is trying to <promptReason>, so the value should be a lowercase sentence fragment. An optional$1placeholder is replaced with the relying party ID (e.g.example.com) of the request being authenticated. Defaults toverify your identity on $1.
platformPasskeysboolean (optional) - Enables passkeys via Apple'sASAuthorizationController. When enabled, passkey operations present the system credential provider sheet (iCloud Keychain, 1Password, Bitwarden, etc.) and credentials sync across the user's devices. 默认值为false. Passingnull/undefined(or omitting the key) leaves the previous setting unchanged.
Configures platform authenticators for the Web Authentication API (navigator.credentials.create() / navigator.credentials.get()). Until this is called, PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() resolves to false and platform-authenticator requests are not serviced.
When touchID is provided, WebAuthn credentials are stored in the macOS keychain and bound to this device's Secure Enclave. Electron automatically generates and persists a per-session metadata secret so that credentials created in one partition are not visible to another.
When platformPasskeys is true, passkey operations use Apple's ASAuthorizationController which delegates to the system's configured Credential Provider Extensions. This enables the same passkey experience as Safari — credentials are available across all devices signed into the same account. Unlike Touch ID credentials, platform passkeys are stored by the credential provider and scoped to the relying party, not to Electron: they are shared across all session partitions and with any other app or browser associated with the same domain. Platform passkeys cannot serve cross-origin (iframe) requests; those requests are left to the other available authenticators (Touch ID supports iframes) and a warning is logged to the DevTools console. The prf and largeBlob WebAuthn extensions are not currently supported by this authenticator — prf inputs are ignored, and a create() call with largeBlob: { support: 'required' } fails.
const { app } = require('electron')
app.configureWebAuthn({
touchID: {
keychainAccessGroup: 'A1B2C3D4E5.com.example.app.webauthn',
promptReason: 'sign in to $1'
},
platformPasskeys: true
})
With the matching entitlements in your app's entitlements.plist:
<key>keychain-access-groups</key>
<array>
<string>A1B2C3D4E5.com.example.app.webauthn</string>
</array>
For platform passkeys, your app needs the Associated Domains entitlement plus an application identifier, both in the same entitlements.plist:
<key>com.apple.developer.associated-domains</key>
<array>
<string>webcredentials:example.com</string>
</array>
<!-- Must match the App ID in your provisioning profile: <TEAM_ID>.<BUNDLE_ID>. -->
<key>com.apple.application-identifier</key>
<string>A1B2C3D4E5.com.example.app</string>
Listing these entitlements is not sufficient on its own — unlike most entitlements, com.apple.developer.associated-domains is provisioning-profile backed. For platform passkeys to work, all of the following must hold:
- In the Apple Developer portal, your App ID (
com.example.app) has the Associated Domains capability enabled, and you have created a provisioning profile for that App ID. - That provisioning profile is embedded in the built app bundle at
Contents/embedded.provisionprofile. This is what authorizes the associated-domains entitlement at runtime; without an embedded profile macOS silently ignores thewebcredentialsassociation and the request fails. (Xcode and@electron/osx-signembed the profile for you; if you sign manually, copy it into the bundle before signing.) - The app is signed (ad-hoc / unsigned builds do not qualify). Both distribution and development signing work — for development builds, use the developer-mode path described below.
com.apple.application-identifiermatches the profile's App ID. Without it,ASAuthorizationControllerfails with "The calling process does not have an application identifier" — this isASAuthorizationErrorcode 1004.- The relying party's domain (
example.comabove) serves a validapple-app-site-associationfile over HTTPS at/.well-known/apple-app-site-associationcontaining awebcredentialsentry whoseappsarray lists this app's<TEAM_ID>.<BUNDLE_ID>. - The relying party ID of each request matches that associated domain.
If these aren't satisfied, ASAuthorizationController fails before it can present the passkey sheet. The request surfaces to the page as a bare NotAllowedError with no further detail (Electron logs an explanatory message to the DevTools console on this path). Because the association is domain-based, platform passkeys always require a real associated domain and its AASA file — there is no localhost rpId escape hatch as there is in browsers.
To test against your domain with a development-signed build (before shipping a distribution profile), append ?mode=developer to the entitlement value and enable developer mode on the machine with swcutil developer-mode -e true. This makes macOS fetch the AASA directly from the domain — bypassing Apple's CDN cache — and honor the association for a development-signed app. You still need the embedded development provisioning profile described above:
<key>com.apple.developer.associated-domains</key>
<array>
<string>webcredentials:example.com?mode=developer</string>
</array>
[!NOTE] Because the request is fulfilled by the system credential provider (not a browser), the
clientDataJSONreturned to the page reportsorigin: "https://<rpId>"— the associated domain — rather than the page's own origin. Relying-party servers that enforce a strictexpectedOriginallowlist must includehttps://<rpId>for verification to succeed. This also means the relying party cannot distinguish which subdomain of the associated domain initiated the ceremony.
[!NOTE] Touch ID WebAuthn credentials are device-bound and are not synced via iCloud Keychain. They are only available on Macs with a Secure Enclave (Apple silicon, or Intel Macs with a T2 chip).
app.disableHardwareAcceleration()
禁用当前应用程序的硬件加速。
这个方法只能在应用程序准备就绪(ready)之前调用。
app.isHardwareAccelerationEnabled()
Returns boolean - whether hardware acceleration is currently enabled.
[!NOTE] This information is only usable after the
gpu-info-updateevent is emitted.
app.disableDomainBlockingFor3DAPIs()
By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU process crashes too frequently. 这个函数会禁用该行为。
这个方法只能在应用程序准备就绪(ready)之前调用。
app.getAppMetrics()
返回 ProcessMetric[]:一个由 ProcessMetric 对象组成的数组,这些对象对应于与应用程序关联的所有进程的内存和 CPU 使用统计信息。
cpu.percentCPUUsage and cpu.idleWakeupsPerSecond are averages over the time since the last call to app.getAppMetrics(), and each call starts a new measurement interval for every process at once. Other code in the main process, including dependencies, shares those intervals. See CPUUsage for more details.
app.getGPUFeatureStatus()
Returns GPUFeatureStatus - The Graphics Feature Status from chrome://gpu/.
[!NOTE] This information is only usable after the
gpu-info-updateevent is emitted.
app.getGPUInfo(infoType)
infoTypestring - 缩放方向,可能是basic或complete。
返回 Promise<unknown>
For infoType equal to complete: Promise is fulfilled with Object containing all the GPU Information as in chromium's GPUInfo object. 这包括 chrome://gpu 页面上显示的版本和驱动程序信息。
对于infoType等于basic: Promise 至少包含当请求complete时的属性Object。下面是一个基础响应示例:
{
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。
Promise is rejected if the GPU is completely disabled, i.e. no hardware and software implementations are available.
app.setBadgeCount([count]) Linux macOS
countInteger (可选) - 如果传入值,则将角标设置为所传入值,否则,在 macOS 上显示一个普通的白点(例如:通知数量未知)。在 Linux 上,如果没有传入值,角标将不会显示。
返回 boolean - 是否调用成功。
为当前应用设置计数器角标。将计数设置为 0 将隐藏角标。
On macOS, it shows on the Dock icon. On Linux, it shows on docks and taskbars that support the LauncherEntry D-Bus API,
[!NOTE] On Linux, the badge is associated with the app's
.desktopfile, soapp.setDesktopName(or thedesktopNamefield inpackage.json) must match the name of the app's actual.desktopfile.
[!NOTE] On macOS, you need to ensure that your application has the permission to display notifications for this method to work.
app.getBadgeCount() macOS
Returns Integer - 获取计数器提醒(badge) 中显示的当前值
app.getLoginItemSettings([options]) macOS Windows
History
| Version(s) | Changes |
|---|---|
None | Removed |
如果你为 app. setLoginItemSettings 提供path 和 args 选项,那么你需要在这里为 openAtLogin 设置相同的参数已确保正确的设置。
返回 Object:
openAtLoginboolean - 如果应用程序设置为在登录时打开, 则为truewasOpenedAtLoginboolean macOS -trueif the app was opened at login automatically.statusstring macOS - can benot-registered,enabled,requires-approval, ornot-found.executableWillLaunchAtLoginboolean Windows -true应用程序被设置为在登录时打开,并且其启动项未停用。该属性与openAtLogin不同,因为它忽略了args选项,如果给定的可执行程序在登录时启动并带有 任意 参数,此属性将为true。launchItemsObject[] Windowsnamestring Windows - 注册表项的名称值。pathstring Windows - 与注册表条目相对应的应用可执行程序。argsstring[] Windows - 传递到可执行文件的命令行参数。scopestring Windows - can beuserormachine. 指示注册表条目是否处于HKEY_CURRENT USER或HKEY_LOCAL_MACHINE下。enabledboolean Windows -true如果应用注册表项已获得启动批准,此时在任务管理器和 Windows 设置中显示为enabled。
app.setLoginItemSettings(settings) macOS Windows
History
| Version(s) | Changes |
|---|---|
None | Removed |
[!IMPORTANT] On macOS, your app should be code signed and notarized for login item settings to work reliably. When an app isn't packaged, code signed, and notarized,
openAtLoginmay silently fail to take effect.
settingsObjectopenAtLoginboolean (可选) -true登录时打开应用程序,false将应用从登录启动项中删除。默认值为false.typestring (optional) macOS - The type of service to add as a login item. 默认值为:mainAppService。mainAppService- 主应用服务。agentService-一个启动代理的属性列表名称。属性列表名称必须与应用的Contents/Library/LaunchAgents目录中的属性列表相对应。daemonServicestring (optional) macOS - The property list name for a launch agent. 属性列表名称必须与应用的Contents/Library/LaunchDaemons目录中的属性列表相对应。loginItemServicestring (optional) macOS - The property list name for a login item service. 属性列表名称必须与应用的Contents/Library/LoginItems目录中的属性列表相对应。
serviceNamestring (optional) macOS - 服务名称。如果type为非默认值,则必填。pathstring (可选) Windows - 登录时运行的可执行文件。默认为process.execPath。argsstring[] (可选) Windows - 传递给可执行文件的控制台参数。默认为空数组。注意用引号包裹路径。enabledboolean (可选) Windows -true将更改已启用的启动注册表项,并在任务管理器和 Windows 设置中启用 / 禁用应用程序。默认值为true。namestring (可选) Windows - 要写入注册表的值名称。默认为应用的 AppUserModelId()。
设置应用程序的登录项设置。
要在 Windows 上使用 Electron 的 autoUpdater(它依赖于 Squirrel),你需要将启动路径设置为可执行文件的名称,但指向上一级目录。这是因为 Squirrel 会自动生成一个存根应用程序(stub application),它会自动启动最新版本。
const { app } = require('electron')
const path = require('node:path')
const appFolder = path.dirname(process.execPath)
const ourExeName = path.basename(process.execPath)
const stubLauncher = path.resolve(appFolder, '..', ourExeName)
app.setLoginItemSettings({
openAtLogin: true,
path: stubLauncher,
args: [
// You might want to pass a parameter here indicating that this
// app was launched via login, but you don't have to
]
})
For more information about setting different services as login items on macOS, see SMAppService.
app.isAccessibilitySupportEnabled() macOS Windows
Returns boolean - true if Chromium's accessibility support is enabled, false otherwise. 如果使用了辅助技术(例如屏幕阅读),该 API 将返回 true。查看更多细节,请查阅 https://www.chromium.org/developers/design-documents/accessibility
app.setAccessibilitySupportEnabled(enabled) macOS Windows
enable逻辑值 - 启用或禁用访问权限树视图。
Manually enables Chromium's accessibility support, allowing to expose accessibility switch to users in application settings. See Chromium's accessibility docs for more details. 默认为禁用
此 API 必须在 ready 事件触发后调用
[!NOTE] Rendering accessibility tree can significantly affect the performance of your app. 默认情况下不应启用该功能。 Calling this method will enable the following accessibility support features:
nativeAPIs,webContents,inlineTextBoxes, andextendedProperties.
app.getAccessibilitySupportFeatures() macOS Windows
Returns string[] - Array of strings naming currently enabled accessibility support components. 可选值:
nativeAPIs- Native OS accessibility APIs integration enabled.webContents- Web contents accessibility tree exposure enabled.inlineTextBoxes- Inline text boxes (character bounding boxes) enabled.extendedProperties- Extended accessibility properties enabled.screenReader- Screen reader specific mode enabled.html- HTML accessibility tree construction enabled.labelImages- Accessibility support for automatic image annotations.pdfPrinting- Accessibility support for PDF printing enabled.
说明:
- The array may be empty if no accessibility modes are active.
- Use
app.isAccessibilitySupportEnabled()for the legacy boolean check; prefer this method for granular diagnostics or telemetry.
示例:
const { app } = require('electron')
app.whenReady().then(() => {
if (app.getAccessibilitySupportFeatures().includes('screenReader')) {
// Change some app UI to better work with Screen Readers.
}
})
app.setAccessibilitySupportFeatures(features) macOS Windows
featuresstring[] - An array of the accessibility features to enable.
可能的值有
nativeAPIs- Native OS accessibility APIs integration enabled.webContents- Web contents accessibility tree exposure enabled.inlineTextBoxes- Inline text boxes (character bounding boxes) enabled.extendedProperties- Extended accessibility properties enabled.screenReader- Screen reader specific mode enabled.html- HTML accessibility tree construction enabled.labelImages- Accessibility support for automatic image annotations.pdfPrinting- Accessibility support for PDF printing enabled.
To disable all supported features, pass an empty array [].
示例:
const { app } = require('electron')
app.whenReady().then(() => {
// Enable a subset of features:
app.setAccessibilitySupportFeatures(['screenReader', 'pdfPrinting', 'webContents'])
// Other logic
// Some time later, disable all features:
app.setAccessibilitySupportFeatures([])
})
app.showAboutPanel()
显示应用程序的"关于"面板选项。这些选项可以被 app.setAboutPanelOptions(可选) 所覆盖。这个函数异步运行。
app.setAboutPanelOptions(options)
选项对象applicationNamestring (可选) - 应用程序的名字applicationVersionstring (可选) - 应用程序版本copyrightstring (可选) - 版权信息versionstring (可选) macOS - 应用程序版本号creditsstring (可选) macOS Windows - 信用信息。authorsstring[] (可选) Linux - 应用程序作者列表。websitestring (可选) Linux - 应用程序的网站。iconPathstring (可选) Linux Windows - 以JPEG 或 PNG 文件格式为应用程序图标路径。在 Linux 上,将显示为 64x64 像素,同时保留纵横比。在 Windows 上,使用 48 x 48 的PNG图片将会有最好的视觉质量。
设置 "关于" 面板选项。这将覆盖应用程序在 macOS 上的 .plist 文件中定义的值。 See the Apple docs for more details. 在 Linux 上,没有默认值,所以必须设置值才能显示。
如果您没有设置 credits 但仍希望在应用中显示它们,AppKit 将在 NSBundle 类的main方法返回的捆绑包中按顺序查找名为"Credits.html", "Credits.rtf"和"Credits.rtfd"的文件。先找到的文件将被使用,如果未找到,则信息区域将留空。 See Apple documentation for more information.
app.isEmojiPanelSupported()
返回 boolean - 当前操作系统是否支持本地 emoji 选择器。
app.showEmojiPanel() macOS Windows
打开系统自身的emjio选取器。
app.startAccessingSecurityScopedResource(bookmarkData) macOS
bookmarkDatastring - base64 编码的安全作用域的书签数据(bookmark data) ,通过dialog.showOpenDialog或者dialog.showSaveDialog方法获取。
返回 Function - 该函数 必须 在你完成访问安全作用域文件后调用一次。 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()
开始访问安全范围内的资源。 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 标志的值是什么。
这个方法只能在应用程序准备就绪(ready)之前调用。
app.isInApplicationsFolder() macOS
返回 boolean - 应用程序当前是否从系统应用程序文件夹运行。与 app.moveToApplicationsFolder()一起使用
app.moveToApplicationsFolder([options]) macOS
返回 boolean - 移动是否成功。请注意,如果移动成功,您的应用程序将退出并重新启动。
默认情况下不会显示确认对话框。如果您希望允许用户确认操作,您可以使用dialog API 进行确认。
**注意:**如果并非是用户造成操作失败,这个方法会抛出错误。例如,如果用户取消了授权会话,这个方法将返回false。如果无法执行复制操作, 则此方法将抛出错误。错误中的信息应该是翔实的,并告诉你到底是哪里出了问题。
默认情况下,如果应用程序目录中存在与被移动的应用同名的应用,并且 未 运行,则已有应用将被丢弃,被移动的应用将顶替其位置。如果应该程序 正在 运行,先运行的应用程序得到焦点,同时之前的程序将退出它自己。此行为可以通过提供可选的冲突处理器来更改,处理器返回的 boolean 将决定移动冲突是否通过默认行为得到解决。即:返回 false 将确保不采取进一步行动,返回 true 将导致默认行为同时方法继续执行。
例如:
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
)
}
}
})
这意味着,如果应用已经存在于用户目录中,如果用户选择 '继续移动',则该功能将继续其默认行为,现有应用将被丢弃,当前应用将移动到其位置。
app.isSecureKeyboardEntryEnabled() macOS
返回 boolean - 是否启用 Secure Keyboard Entry 。
默认情况下,此 API 将返回 false。
app.setSecureKeyboardEntryEnabled(enabled) macOS
enabledboolean - 启用或禁用Secure Keyboard Entry
在应用中启用 Secure Keyboard Entry 。
通过使用此 API,可以防止密码和其他敏感信息等重要信息被其他进程截获。
See Apple's documentation for more details.
[!NOTE] Enable
Secure Keyboard Entryonly when it is needed and disable it when it is no longer needed.
app.setProxy(config)
configProxyConfig
返回 Promise<void> - 代理设置进程完成。
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).
这个方法只能在应用程序准备就绪(ready)之后调用。
app.resolveProxy(url)
urlURL
Returns Promise<string> - Resolves with the proxy information for url that will be used when attempting to make requests using Net in the utility process.
app.setClientCertRequestPasswordHandler(handler) Linux
-
handlerFunction<Promise<string>>clientCertRequestParamsObjecthostnamestring - the hostname of the site requiring a client certificatetokenNamestring - the token (or slot) name of the cryptographic deviceisRetryboolean - whether there have been previous failed attempts at prompting the password
Returns
Promise<string>- Resolves with the password
The handler is called when a password is needed to unlock a client certificate for hostname.
const { app } = require('electron')
async function passwordPromptUI(text) {
return new Promise((resolve, reject) => {
// display UI to prompt user for password
// ...
// ...
resolve('the password')
})
}
app.setClientCertRequestPasswordHandler(async ({ hostname, tokenName, isRetry }) => {
const text = `Please sign in to ${tokenName} to authenticate to ${hostname} with your certificate`
const password = await passwordPromptUI(text)
return password
})
属性
app.accessibilitySupportEnabled macOS Windows
A boolean property that's true if Chromium's accessibility support is enabled, false otherwise. 如果使用了辅助功能(例如屏幕阅读),该 API 将返回 true。 Setting this property to true manually enables Chromium's accessibility support, allowing developers to expose accessibility switch to users in application settings.
See Chromium's accessibility docs for more details. 默认为禁用
此 API 必须在 ready 事件触发后调用
[!NOTE] Rendering accessibility tree can significantly affect the performance of your app. 默认情况下不应启用该功能。
app.applicationMenu
一个 Menu | null 类型的属性,如果已设置了菜单 (Menu),则返回 Menu,否则返回 null。用户可以通过传递一个 Menu 来设置此属性。
app.badgeCount Linux macOS
返回当前应用角标计数的 Integer 属性。将计数设置为 0 将隐藏角标。 Setting this with any nonzero integer shows the count on the Dock icon on macOS, or on the launcher on Linux.
[!NOTE] On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect.
app.commandLine 只读
一个 CommandLine 对象,允许您读取和操作 Chromium 使用的命令行参数。
app.dock macOS Readonly
一个 Dock | undefined 类型的属性(在 macOS 上是 Dock,在其他平台上则是 undefined),它允许您对用户 Dock 中的 app 图标执行操作。
app.isPackaged 只读
返回一个boolean值,如果应用已经打包,返回true ,否则返回false 。对于大多数应用程序,此属性可用于区分开发和生产环境。
app.toastActivatorCLSID Windows Readonly
A string property that returns the app's Toast Activator CLSID.
app.name
string 属性,指明当前应用程序的名称,即应用程序 package.json 文件中的名称。
根据 npm 的命名规则, 通常 package.json 中的 name 字段是一个短的小写字符串。通常还应该指定一个 productName 字段, 是首字母大写的完整名称,用于表示应用程序的名称。Electron 会优先使用这个字段作为应用名。
On Windows, the application's name must not contain reserved filename characters, because it is used to construct the default userData directory.
app.userAgentFallback
string Electron 用于全局回退的用户代理字符串。
当用户代理在webContents 或 session 级别没有被设置时,将使用此用户代理。有助于确保您的整个应用程序具有相同的用户代理。在应用初始化中尽早设置为自定义值,以确保使用的是您覆盖的值。
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).
您可以使用此属性来提示用户下载应用程序的 arm64 版本,当用户错误地在转译环境(Rosetta 或 WOW)下运行 x64 版本。