跳转到主内容

app

控制应用程序的事件生命周期。

Process: Main

下面的这个例子将会展示如何在最后一个窗口被关闭时退出应用:

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'

返回:

当 Electron 完成初始化时,发出一次。 在 macOS 上,如果通过通知中心启动应用程序,launchInfo 保存 NSUserNotificationuserInfoUNNotificationResponse 的信息。 你也可以通过调用 app.isReady() 来检查该事件是否已被触发,以及通过 app.whenReady() 得到一个当Electron已初始化后fulfill 的 Promise。

[!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'

当所有的窗口都被关闭时触发。

如果你没有监听此事件并且所有窗口都关闭了,默认的行为是控制退出程序;但如果你监听了此事件,你可以控制是否退出程序。 如果用户按下了 Cmd + Q,或者开发者调用了 app.quit(),Electron 会首先关闭所有的窗口然后触发 will-quit 事件,在这种情况下 window-all-closed 事件不会被触发。

事件:'before-quit'

返回:

  • event Event

在程序关闭窗口前发信号。 调用 event.preventDefault() 将阻止终止应用程序的默认行为。

[!NOTE] If application quit was initiated by autoUpdater.quitAndInstall(), then before-quit is emitted after emitting close event on all windows and closing them.

[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。

事件: 'will-quit'

返回:

  • event Event

当所有窗口被关闭后触发,同时应用程序将退出。 调用 event.preventDefault() 将阻止终止应用程序的默认行为。

关于 window-all-closedwill-quit 事件之间的差异, 请参见 window-all-closed 事件的说明。

[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。

事件: 'quit'

返回:

  • event Event
  • exitCode Integer

在应用程序退出时发出。

[!NOTE] 在 Windows 系统中,如果应用程序因关机/重启而关闭,那么这个事件将不会被触发。

事件: 'open-file' macOS

返回:

  • event Event
  • path string

当用户想要在应用中打开一个文件时发出。 open-file 事件通常在应用已经打开,并且系统要再次使用该应用打开文件时发出。 open-file也会在一个文件被拖到 dock 并且还没有运行的时候发出。 请确认在应用启动的时候(甚至在 ready 事件发出前) 就对 open-file 事件进行监听。

如果你想处理这个事件,你应该调用 event.preventDefault()

在 Windows 系统中,你需要解析 process.argv (在主进程中) 来获取文件路径

事件: 'open-url' macOS

返回:

  • event Event
  • url string

当用户想要在应用中打开一个 URL 时发出。 你的应用程序的 Info. plist 文件必须在 CFBundleURLTypes 这个key中定义 url scheme, 并将 NSPrincipalClass 设置为 AtomApplication

open-file 事件一样,请务必在应用程序启动时尽早注册 open-url 事件的侦听器,以检测应用程序是否正在被某个 URL 打开。 如果在 ready 事件回调中注册侦听器,您将错过触发应用程序启动的 URL 。

事件: 'activate' macOS

返回:

  • event Event
  • hasVisibleWindows boolean

当应用被激活时发出。 各种操作都可以触发此事件, 例如首次启动应用程序、尝试在应用程序已运行时或单击应用程序的坞站或任务栏图标时重新激活它。

事件: 'did-become-active' macOS

返回:

  • event Event

当应用即将被激活时触发。 不同于 activate 事件,did-become-active 事件将在每次程序被激活前都触发,而不仅仅是 Dock 图标被点击或者应用重启。 当用户通过 macOS 应用切换器切换到程序时也会被触发。

事件: 'did-rele-active' macOS

返回:

  • event Event

当程序长时间处于非激活(Active)、非聚焦(focus)状态时触发。 例如:点击其他应用,或者通过应用切换器切换到其他应用时,就会被触发。

Event: 'continue-activity' macOS

返回:

  • event Event
  • typestring-标识活动的字符串。 Maps to NSUserActivity.activityType.
  • userInfo unknown - 包含另一个设备上activity存储的应用特定状态。
  • details Object
    • webpageURL string (可选) - 如果可用,可识别另一设备上活动访问的网页的 URL 的字符串。

Handoff 期间,当来自其他设备的活动需要恢复时,也会触发。 如果你想处理这个事件,你应该调用 event.preventDefault()

只有具有支持相应的活动类型并且相同的开发团队 ID 作为启动程序时,用户行为才会进行。 所支持活动类型已在应用的 Info.plist 中的 NSUserActivityTypes 里明确定义。

Event: 'will-continue-activity' macOS

返回:

Handoff 期间,当来自其他设备的活动需要恢复前触发。 如果你想处理这个事件,你应该调用 event.preventDefault()

Event: 'continue-activity-error' macOS

返回:

Handoff 期间,当来自其他设备的活动恢复失败时触发。

Event: 'activity-was-continued' macOS

返回:

  • event Event
  • typestring-标识活动的字符串。 Maps to NSUserActivity.activityType.
  • userInfo unknown - 包含activity存储的应用特定状态。

Handoff 期间,当来自此设备的活动在其他设备恢复时触发。

Event: 'update-activity-state' macOS

返回:

  • event Event
  • typestring-标识活动的字符串。 Maps to NSUserActivity.activityType.
  • userInfo unknown - 包含activity存储的应用特定状态。

Handoff 期间,当来自此设备的活动在其他设备即将恢复时触发。 如果需要更新要传输的状态,你应该立即调用 event.preventDefault(), 构造新的 userInfo 字典,并及时调用 app.updateCurrentActiviy()。 否则,操作会失败,并且触发 continue-activity-error

事件: 'new-window-for-tab' macOS

返回:

  • event Event

当用户点击原生的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'

返回:

browserWindow 失去焦点时触发。

事件: 'browser-window-focus'

返回:

browserWindow 获得焦点时触发。

事件: 'browser-window-created'

返回:

当一个新的 browserWindow 被创建时触发。

事件: 'web-contents-created'

返回:

当一个新的 webContents 被创建时触发。

事件: 'certificate-error'

返回:

  • event Event
  • webContents WebContents
  • url string
  • error string - 错误码
  • certificate Certificate
  • callback Function
    • isTrusted boolean - 是否将证书视为受信任。
  • isMainFrame boolean

当对 urlcertificate 证书验证失败的时候发出。如果需要信任这个证书,你需要阻止默认行为 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'

返回:

当一个客户证书被请求的时候发出。

url 指的是请求客户端认证的网页地址,调用 callback 时需要传入一个证书列表中的证书。 需要通过调用 event.preventDefault() 来防止应用自动使用第一个证书进行验证。

const { app } = require('electron')

app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})

事件: "login"

返回:

  • event Event
  • webContents WebContents (可选)
  • authenticationResponseDetails Object
    • url URL
    • pid number
  • authInfo Object
    • isProxy boolean
    • scheme string
    • host string
    • port Integer
    • realm string
  • callback Function
    • username string (可选)
    • password string (可选)

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'

返回:

渲染器进程意外消失时触发。 这种情况通常因为进程崩溃或被杀死。

事件: 'child-process-gone'

返回:

  • event Event
  • details Object
    • type string - 进程类型。 以下值之一:
      • Utility
      • Zygote
      • Sandbox helper
      • GPU
      • Pepper Plugin
      • Pepper Plugin Broker
      • Unknown
    • reason string - 子进程结束的原因。 可选值:
      • 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
    • exitCode number -进程的退出代码(例如,如果在 POSIX 上,则来自 waitpid 的状态,在 Windows 上来自 GetExitCodeProcess)。
    • serviceName string (可选) - 进程的非本地化名称。
    • name string (可选) - 进程的名称。 功能性示例: Audio Service, Content Decryption Module Service, Network Service, Video Capture, 等等。

子进程意外消失时触发。 这种情况通常因为进程崩溃或被杀死。 子进程不包括渲染器进程。

事件: "accessibility-support-changed" _ macOS _ _ Windows _

返回:

  • event Event
  • accessibilitySupportEnabled boolean - 当开启了 Chrome 辅助功能支持为 true,否则为 false

当 Chrome 的辅助功能状态改变时触发。 当启用或禁用辅助技术时将触发此事件,例如屏幕阅读器 。 查看更多详情 https://www.chromium.org/developers/design-documents/accessibility

事件:'session-created'

返回:

当 Electron创建了一个新的 session后被触发.

const { app } = require('electron')

app.on('session-created', (session) => {
console.log(session)
})

事件: 'second-instance'

返回:

  • event Event
  • argv string[] - 第二实例命令行参数的数组。
  • workingDirectory string - 第二实例的工作目录。
  • additionalData unknown - 第二个实例发送过来的额外的 JSON 对象

当第二个实例被执行并且调用 app.requestSingleInstanceLock() 时,这个事件将在你的应用程序的首个实例中触发

argv 是第二个实例的命令行参数的数组, workingDirectory 是这个实例当前工作目录。 通常, 应用程序会激活窗口并且取消最小化来响应。

note

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 argv array will not include the arguments.

保证在 appready 事件发出后发出此事件。

[!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 事件, 并且默认情况下应用程序将终止。

此方法会确保执行所有beforeunloadunload事件处理程序。 可以在退出窗口之前的beforeunload事件处理程序中返回false取消退出。

app.exit([exitCode])

  • exitCode Integer (可选)

使用 exitCode 立即退出。 exitCode 默认为0。

所有窗口都将立即被关闭,而不询问用户,而且 before-quitwill-quit 事件也不会被触发。

app.relaunch([options])

  • options Object (可选)
    • args string[] (可选)
    • execPath string (可选)

在当前实例退出时重新启动应用程序。

默认情况下,新实例将使用与当前实例相同的工作目录和命令行参数。 当指定了 args 时,args 将作为命令行参数传递。 当指定了 execPath 时,execPath 将被执行以重新启动,而不是当前应用程序。

请注意,此方法在执行时并不会退出应用程序。 在调用 app.relaunch 后,必须调用 app.quitapp.exit 才能使应用程序重新启动。

当多次调用 app.relaunch 时,当前实例退出后将启动多个实例。

一个立即重启当前实例并向新实例添加命令行参数的示例:

const { app } = require