Electron app事件,方法,屬性(生命周期)


參考:https://www.electronjs.org/docs/api/app

官網的訪問比較慢,這里復制過來,並加點自己的理解

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

進程:主進程

下面的這個例子將會展示如何在最后一個窗口被關閉時退出應用:

const { app } = require('electron')
app.on('window-all-closed', () => {
  app.quit()
})

事件

app 對象會發出以下事件:

事件: 'will-finish-launching'

當應用程序完成基礎的啟動的時候被觸發。 在 Windows 和 Linux 中, will-finish-launching 事件與 ready 事件是相同的; 在 macOS 中,這個事件相當於 NSApplication 中的 applicationWillFinishLaunching 提示。 通常會在這里為 open-fileopen-url 設置監聽器,並啟動崩潰報告和自動更新。

絕大部分情況下,你必須在ready事件句柄中處理所有事務。

EN

事件: 'ready'

返回:

  • event Event
  • launchInfo Record<string, any> macOS

當 Electron 完成初始化時,發出一次。 On macOS, launchInfo holds the userInfo of the NSUserNotification 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.

EN

事件: 'window-all-closed'

當所有的窗口都被關閉時觸發。

如果你沒有監聽此事件並且所有窗口都關閉了,默認的行為是控制退出程序;但如果你監聽了此事件,你可以控制是否退出程序。 如果用戶按下了 Cmd + Q,或者開發者調用了 app.quit(),Electron 會首先關閉所有的窗口然后觸發 will-quit 事件,在這種情況下 window-all-closed 事件不會被觸發。

事件:'before-quit'

返回:

  • event Event

在程序關閉窗口前發信號。 Calling event.preventDefault() will prevent the default behavior, which is terminating the application.

注意: 如果由 autoUpdater.quitAndInstal() 退出應用程序 ,那么在所有窗口觸發 close 之后 才會觸發 before-quit 並關閉所有窗口。

注:在 Windows 系統中,如果應用程序因系統關機/重啟或用戶注銷而關閉,那么這個事件不會被觸發。

EN

事件: 'will-quit'

返回:

  • event Event

Emitted when all windows have been closed and the application will quit. Calling event.preventDefault() will prevent the default behavior, which is terminating the application.

關於 window-all-closedwill-quit 事件之間的差異, 請參見 window-all-closed 事件的說明。

注:在 Windows 系統中,如果應用程序因系統關機/重啟或用戶注銷而關閉,那么這個事件不會被觸發。

EN

事件: 'quit'

返回:

  • event Event
  • exitCode Integer

在應用程序退出時發出。

注:在 Windows 系統中,如果應用程序因系統關機/重啟或用戶注銷而關閉,那么這個事件不會被觸發。

EN

事件: 'open-file' macOS

返回:

  • event Event
  • path String

當用戶想要在應用中打開一個文件時發出。 open-file 事件通常在應用已經打開,並且系統要再次使用該應用打開文件時發出。 open-file也會在一個文件被拖到 dock 並且還沒有運行的時候發出。 請確認在應用啟動的時候(甚至在 ready 事件發出前) 就對 open-file 事件進行監聽。

如果你想處理這個事件,你應該調用 event.preventDefault()

在 Windows 系統中,你需要解析 process.argv (在主進程中) 來獲取文件路徑

EN

事件: 'open-url' macOS

返回:

  • event Event
  • url String

當用戶想要在應用中打開一個 URL 時發出。 Your application's Info.plist file must define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.

如果你想處理這個事件,你應該調用 event.preventDefault()

EN

事件: 'activate' macOS

返回:

  • event Event
  • hasVisibleWindows Boolean

當應用被激活時發出。 各種操作都可以觸發此事件, 例如首次啟動應用程序、嘗試在應用程序已運行時或單擊應用程序的塢站或任務欄圖標時重新激活它。

EN

事件: 'did-groupe-active' macOS

返回:

  • event Event

當應用被激活時發出。 與 activate 事件的不同是應用,程序激活時都會觸發 did-become-active ,而不僅僅在 Dock 圖標被點擊或應用程序被重新啟動的時候。

EN

事件: 'continue-activity' macOS

返回:

  • event Event
  • typeString-標識活動的字符串。 映射到 NSUserActivity. activityType
  • userInfo unknown - Contains app-specific state stored by the activity on another device.

當來自不同設備的活動通過 Handoff 想要恢復時觸發。 如果你想處理這個事件,你應該調用 event.preventDefault()

只有具有支持相應的活動類型並且相同的開發團隊 ID 作為啟動程序時,用戶行為才會進行。 所支持活動類型已在應用的 Info.plist 中的 NSUserActivityTypes 里明確定義。

EN

事件: 'will-continue-activity' macOS

返回:

當來自不同設備的活動通過 Handoff 恢復之前觸發。 如果你想處理這個事件,你應該調用 event.preventDefault()

EN

事件: 'continue-activity-error' macOS

返回:

當來自不同設備的活動通過 Handoff 恢復失敗時觸發。

EN

事件: 'activity-was-continued' macOS

返回:

  • event Event
  • typeString-標識活動的字符串。 映射到 NSUserActivity. activityType
  • userInfo unknown - Contains app-specific state stored by the activity.

當來自不同設備的活動通過 Handoff 成功恢復后觸發。

EN

事件: 'update-activity-state' macOS

返回:

  • event Event
  • typeString-標識活動的字符串。 映射到 NSUserActivity. activityType
  • userInfo unknown - Contains app-specific state stored by the activity.

Handoff 即將通過另一個設備恢復時觸發。 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. 否則,操作會失敗,並且觸發 continue-activity-error

EN

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

返回:

  • event Event

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

EN

事件: 'browser-window-blur'

返回:

browserWindow 失去焦點時發出。

EN

事件: 'browser-window-focus'

返回:

browserWindow 獲得焦點時發出。

EN

事件: 'browser-window-created'

返回:

在創建新的 browserWindow 時發出。

EN

事件: 'web-contents-created'

返回:

在創建新的 webContents 時發出。

EN

事件: 'certificate-error'

返回:

  • event Event

  • webContents WebContents

  • url String

  • error String - 錯誤碼

  • certificate 證書

  •   callback
    

    Function

    • isTrustedBoolean-是否將證書視為可信的

當對 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)
  }
})
復制

EN

事件: 'select-client-certificate'

返回:

  • event Event

  • webContents WebContents

  • url URL

  • certificateList [證書]

  •   callback
    

    Function

當一個客戶證書被請求的時候發出。

url 指的是請求客戶端認證的網頁地址,調用 callback 時需要傳入一個證書列表中的證書。 需要通過調用 event.preventDefault() 來防止應用自動使用第一個證書進行驗證。

const { app } = require('electron')

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

EN

事件: "login"

返回:

  • event Event

  • webContents WebContents

  •   authenticationResponseDetails
    

    Object

    • url URL
  •   authInfo
    

    Object

    • isProxy Boolean
    • scheme String
    • host String
    • port Integer
    • realm String
  •   callback
    

    Function

    • username String (optional)
    • password String (optional)

webContents 要進行基本身份驗證時觸發。

默認行為是取消所有身份驗證。 默認行為是取消所有的驗證行為,如果需要重寫這個行為,你需要用 event.preventDefault() 來阻止默認行為,並且使用 callback(username, password) 來驗證。

const { app } = require('electron')

app.on('login', (event, webContents, details, authInfo, callback) => {
  event.preventDefault()
  callback('username', 'secret')
})
復制

If callback is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page.

EN

Event: 'gpu-info-update'

Emitted whenever there is a GPU info update.

EN

事件: 'gpu-process-crashed' 已廢棄

返回:

  • event Event
  • killed Boolean

當gpu進程崩潰或關閉(殺死)時觸發

已廢棄:這個事件被包含更多子進程退出信息原因的child-process-gone事件取代了。 It isn't always because it crashed. The killed boolean can be replaced by checking reason === 'killed' when you switch to that event.

EN

Event: 'renderer-process-crashed' Deprecated

返回:

當渲染器進程webContents崩潰或關閉(殺死)時觸發。

已廢棄: 此事件被包含更多關於渲染過程為何消失的信息的 render-process-gone 事件替代了 It isn't always because it crashed. The killed boolean can be replaced by checking reason === 'killed' when you switch to that event.

EN

Event: 'render-process-gone'

返回:

  • event Event

  • webContents WebContents

  •   details
    

    Object

    •   reason
      

      String - The reason the render process is gone. 可選值:

      • clean-exit - Process exited with an exit code of zero
      • abnormal-exit - Process exited with a non-zero exit code
      • killed - Process was sent a SIGTERM or otherwise killed externally
      • crashed - Process crashed
      • oom - Process ran out of memory
      • launch-failed - Process never successfully launched
      • integrity-failure - Windows code integrity checks failed

Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.

EN

Event: 'child-process-gone'

返回:

  • event Event

  •   details
    

    Object

    •   type
      

      String - Process type. One of the following values:

      • Utility
      • Zygote
      • Sandbox helper
      • GPU
      • Pepper Plugin
      • Pepper Plugin Broker
      • Unknown
    •   reason
      

      String - The reason the child process is gone. 可選值:

      • clean-exit - Process exited with an exit code of zero
      • abnormal-exit - Process exited with a non-zero exit code
      • killed - Process was sent a SIGTERM or otherwise killed externally
      • crashed - Process crashed
      • oom - Process ran out of memory
      • launch-failed - Process never successfully launched
      • integrity-failure - Windows code integrity checks failed
    • exitCode Number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows).

    • name String (optional) - The name of the process. i.e. for plugins it might be Flash. 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.

EN

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

返回:

  • event Event
  • accessibilitySupportEnabled當啟用了 Chrome 的輔助功能時為 true, 其他情況為 false

當 Chrome 的輔助功能狀態改變時觸發。 當啟用或禁用輔助技術時將觸發此事件,例如屏幕閱讀器 。 查看更多詳情 chromium.org/developers/design-documents/accessibility

EN

事件:'session-created'

返回:

當 Electron創建了一個新的 session后被觸發.

const { app } = require('electron')

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

EN

事件: 'second-instance'

返回:

  • event Event
  • argv String[] - 第二個實例的命令行參數數組
  • workingDirectory String - 第二個實例的工作目錄

當第二個實例被執行並且調用 app.requestSingleInstanceLock() 時,這個事件將在你的應用程序的首個實例中觸發

argv 是第二個實例的命令行參數的數組, workingDirectory 是這個實例當前工作目錄。 通常, 應用程序會激活窗口並且取消最小化來響應。

Note: If the second instance is started by a different user than the first, the argv array will not include the arguments.

保證在 appready 事件發出后發出此事件。

注意: 額外命令行參數可能由 Chromium 添加, ,例如 --original-process-start-time

EN

事件: 'desktop-capturer-get-sources'

返回:

Emitted when desktopCapturer.getSources() is called in the renderer process of webContents. Calling event.preventDefault() will make it return empty sources.

EN

事件: 'remote-require'

返回:

  • event Event
  • webContents WebContents
  • moduleName String

webContents 的渲染器進程中調用 remote.require() 時發出。 調用 event.preventDefault() 將阻止模塊返回。 可以通過設置 event.returnValue 返回自定義值。

EN

事件: 'remote-get-global'

返回:

  • event Event
  • webContents WebContents
  • globalName String

webContents 的渲染器進程中調用 remote.getGlobal() 時發出。 調用 event.preventDefault() 將阻止全局返回。 可以通過設置 event.returnValue 返回自定義值。

EN

事件: 'remote-get-builtin'

返回:

  • event Event
  • webContents WebContents
  • moduleName String

webContents 的渲染器進程中調用 remote.getBuiltin() 時發出。 調用 event.preventDefault() 將阻止模塊返回。 可以通過設置 event.returnValue 返回自定義值。

EN

事件: 'remote-get-current-window'

返回:

webContents 的渲染器進程中調用 remote.getCurrentWindow() 時發出。 調用 event.preventDefault() 將阻止對象返回 可以通過設置 event.returnValue 返回自定義值。

EN

事件: 'remote-get-current-web-contents'

返回:

webContents 的渲染器進程中調用 remote.getCurrentWebContents() 時發出。 調用 event.preventDefault() 將阻止對象返回 可以通過設置 event.returnValue 返回自定義值。

EN

方法

app 對象具有以下方法:

注意: 某些方法僅在特定的操作系統上可用, 這些方法會被標記出來。

EN

app.quit()

嘗試關閉所有窗口 將首先發出 before-quit 事件。 如果所有窗口都已成功關閉, 則將發出 will-quit 事件, 並且默認情況下應用程序將終止。

此方法會確保執行所有beforeunloadunload事件處理程序。 可以在退出窗口之前的beforeunload事件處理程序中返回false取消退出。

EN

app.exit([exitCode\])

  • exitCode Integer (可選)

Exits immediately with exitCode. exitCode defaults to 0.

所有窗口都將立即被關閉,而不詢問用戶,而且 before-quitwill-quit 事件也不會被觸發。

EN

app.relaunch([options\])

  •   options
    

    Object (可選)

    • args String[] (可選)
    • execPath String (可選)

從當前實例退出,重啟應用。

默認情況下,新的實例將會使用和當前實例相同的工作目錄以及命令行參數。 當設置了 args 參數時, args 將作為命令行參數傳遞。 當設置了 execPathexecPath 將被執行以重新啟動,而不是當前的應用程序。

請注意, 此方法在執行時不會退出當前的應用程序, 你需要在調用 app.relaunch 方法后再執行 app. quit 或者 app.exit 來讓應用重啟。

app.relaunch 被多次調用時,多個實例將在當前實例退出后啟動。

立即重啟當前實例並向新的實例添加新的命令行參數的示例:

const { app } = require('electron')

app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0)
復制

EN

app.isReady()

返回 Boolean 類型 - 如果 Electron 已經完成初始化,則返回 true, 其他情況為 false See also app.whenReady().

EN

app.whenReady()

返回 Promise<void> - 當Electron 初始化完成。 可用作檢查 app.isReady() 的方便選擇,假如應用程序尚未就緒,則訂閱ready事件。

EN

app.focus([options\])

  •   options
    

    Object (可選)

    • steal Boolean macOS - Make the receiver the active app even if another app is currently active.

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.

You should seek to use the steal option as sparingly as possible.

EN

app.hide() macOS

隱藏所有的應用窗口,不是最小化.

EN

app.show() macOS

Shows application windows after they were hidden. Does not automatically focus them.

EN

app.setAppLogsPath([path\])

  • path String (optional) - A custom path for your logs. Must be absolute.

Sets or creates a directory your app's logs which can then be manipulated with app.getPath() or app.setPath(pathName, newPath).

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.

EN

app.getAppPath()

返回 String 類型 - 當前應用程序所在目錄

EN

app.getPath(name)

  •   name
    

    String - You can request the following paths by the name:

    • home 用戶的 home 文件夾(主目錄)

    •   appData
      

      Per-user application data directory, which by default points to:

      • %APPDATA% Windows 中
      • $XDG_CONFIG_HOME or ~/.config Linux 中
      • ~/Library/Application Support macOS 中
    • userData 儲存你應用程序設置文件的文件夾,默認是 appData 文件夾附加應用的名稱

    • 緩存

    • temp 臨時文件夾

    • exe當前的可執行文件

    • module The libchromiumcontent

    • desktop 當前用戶的桌面文件夾

    • documents 用戶文檔目錄的路徑

    • downloads 用戶下載目錄的路徑

    • music 用戶音樂目錄的路徑

    • pictures 用戶圖片目錄的路徑

    • videos 用戶視頻目錄的路徑

    • recent Directory for the user's recent files (Windows only).

    • logs應用程序的日志文件夾

    • pepperFlashSystemPlugin Pepper Flash 插件的系統版本的完成路徑。

    • crashDumps Directory where crash dumps are stored.

Returns String - A path to a special directory or file associated with name. On failure, an Error is thrown.

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.

EN

app.getFileIcon(path[, options\])

  • path String

  •   options
    

    Object (可選)

    •   size
      

      String

      • small - 16x16
      • normal - 32x32
      • large - Linux上是 48x48, Windows 上是 32x32, macOS 中無效

返回 Promise<NativeImage> - 完成后返回當前應用的圖標, 類型是 NativeImage.

讀取文件的關聯圖標。

Windows 上, 會有兩種圖標:

  • 與某些文件擴展名相關聯的圖標, 比如 . mp3 . png 等。
  • 文件本身就帶圖標,像是 .exe, .dll, .ico

LinuxmacOS 系統中,圖標取決於和應用程序綁定的 文件 mime 類型

EN

app.setPath(name, path)

  • name String
  • path String

重寫 name 的路徑為 path,一個特定的文件夾或者文件。 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.

name 參數只能使用 app.getPath 定義過的 name

默認情況下, 網頁的 cookie 和緩存將存儲在 userData 目錄下。 如果要更改這個位置, 你需要在 app 模塊中的 ready 事件被觸發之前重寫 userData 的路徑。

EN

app.getVersion()

返回 String-加載的應用程序的版本。 如果應用程序的 package. json 文件中找不到版本號, 則返回當前包或者可執行文件的版本。

EN

app.getName()

返回 String-當前應用程序的名稱, 它是應用程序的 package. json 文件中的名稱。

Usually the name field of package.json is a short lowercase name, according to the npm modules spec. 通常還應該指定一個 productName 字段, 是首字母大寫的完整名稱,用於表示應用程序的名稱。Electron 會優先使用這個字段作為應用名。

EN

app.setName(name)

  • name String

設置當前應用程序的名字

Note: This function overrides the name used internally by Electron; it does not affect the name that the OS uses.

EN

app.getLocale()

Returns String - The current application locale. Possible return values are documented here.

要設置區域,則需要在應用啟動時使用命令行時打開開關,你可以在這里找到。

注意: 分發打包的應用程序時, 你必須指定 locales 文件夾。

注意: 在 Windows 上,你必須得等 ready 事件觸發之后,才能調用該方法

EN

app.getLocaleCountryCode()

Returns String - User operating system's locale two-letter ISO 3166 country code. The value is taken from native OS APIs.

注意: 當無法檢測本地國家代碼時,它返回空字符串。

EN

app.addRecentDocument(path) macOS**Windows

  • path String

將此 path 添加到最近打開的文件列表中

This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu.

EN

app.clearRecentDocuments() macOS**Windows

清空最近打開的文檔列表

EN

app.setAsDefaultProtocolClient(protocol[, path, args\])

  • protocol String - 協議的名稱, 不包含 ://。 For example, if you want your app to handle electron:// links, call this method with electron as the parameter.
  • path String (optional) Windows - The path to the Electron executable. Defaults to process.execPath
  • args String[] (optional) Windows - Arguments passed to the executable. Defaults to an empty array

返回 Boolean-是否成功調用。

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.

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. 有關詳細信息,請參閱 Apple's documentation

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.

The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.

EN

app.removeAsDefaultProtocolClient(protocol[, path, args\]) macOS**Windows

  • protocol String - 協議的名稱, 不包含 ://
  • pathString (可選) Windows -默認為 process.execPath
  • args String[] (可選) Windows - 默認為空數組

返回 Boolean-是否成功調用。

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.

EN

app.isDefaultProtocolClient(protocol[, path, args\])

  • protocol String - 協議的名稱, 不包含 ://
  • pathString (可選) Windows -默認為 process.execPath
  • args String[] (可選) Windows - 默認為空數組

Returns Boolean - Whether the current executable is the default handler for a protocol (aka URI scheme).

注意: 在macOS上, 您可以使用此方法檢查應用程序是否已注冊為協議的默認協議處理程序。 同時可以通過查看 ~/Library/Preferences/com.apple.LaunchServices.plist 來確認。 有關詳細信息,請參閱 Apple's documentation

The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.

EN

app.getApplicationNameForProtocol(url)

  • 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://).

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.

This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL.

EN

app.getApplicationInfoForProtocol(url) macOS**Windows

  • url String - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including :// at a minimum (e.g. https://).

Returns Promise<Object> - Resolve with an object containing the following:

  • icon NativeImage - the display icon of the app handling the protocol.
  • path String - installation path of the app handling the protocol.
  • name String - display name of the app handling the protocol.

This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL.

EN

app.setUserTasks(tasks) Windows

  • tasks [Task] - 由 Task 對象組成的數組

Adds tasks to the Tasks category of the Jump List on Windows.

tasksTask 對象組成的數組

返回 Boolean-是否成功調用。

注意: 如果您想自定義跳轉列表, 請使用 aapp.setJumpList(categories) 來代替。

EN

app.getJumpListSettings() Windows

返回 Object:

  • minItems Integer - 將在跳轉列表中顯示項目的最小數量(有關此值的更詳細描述,請參閱 MSDN docs).
  • removedItems [JumpListItem] - Array of JumpListItem objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. 這些項目不能在 next 調用 app.setJumpList() 時重新添加到跳轉列表中, Windows不會顯示任何包含已刪除項目的自定義類別.

EN

app.setJumpList(categories) Windows

  • categories [JumpListCategory] | null - Array of JumpListCategory objects.

設置或刪除應用程序的自定義跳轉列表,並返回以下字符串之一:

  • ok - 沒有出現錯誤
  • error - 發生一個或多個錯誤,啟用運行日志記錄找出可能的原因。
  • invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard Tasks category.
  • fileTypeRegistrationError -嘗試向自定義跳轉列表添加一個文件鏈接,但是該應用未注冊處理該應用類型
  • customCategoryAccessDeniedError - 由於用戶隱私或策略組設置,自定義類別無法添加到跳轉列表。

如果 categories 的值為 null, 之前設定的自定義跳轉列表(如果存在) 將被替換為標准的應用跳轉列表(由windows生成)

Note: If a JumpListCategory object has neither the type nor the name property set then its type is assumed to be tasks. 如果設置了 name 屬性,省略了 type 屬性,那么 type 默認為 custom.

注意: 用戶可以從自定義類別中移除項目, after 調用 app.setJumpList(categories) 方法之前, Windows不允許刪除的項目添加回自定義類別。 嘗試提前將刪除的項目重新添加 到自定義類別中,將導致整個自定義類別被隱藏。 刪除的項目可以使用 app.getJumpListSettings() 獲取。

下面是創建自定義跳轉列表的一個非常簡單的示例:

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' }
    ]
  },
  { // 已經有一個名字所以 `type` 被認為是 "custom"
    name: 'Tools',
    items: [
      {
        type: 'task',
        title: 'Tool A',
        program: process.execPath,
        args: '--run-tool-a',
        icon: process.execPath,
        iconIndex: 0,
        description: 'Runs Tool A'
      },
      {
        type: 'task',
        title: 'Tool B',
        program: process.execPath,
        args: '--run-tool-b',
        icon: process.execPath,
        iconIndex: 0,
        description: 'Runs Tool B'
      }
    ]
  },
  { type: 'frequent' },
  { //這里沒有設置名字 所以 `type` 被認為是 "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'
      }
    ]
  }
])
復制

EN

app.requestSingleInstanceLock()

返回 Boolean

此方法的返回值表示你的應用程序實例是否成功取得了鎖。 如果它取得鎖失敗,你可以假設另一個應用實例已經取得了鎖並且仍舊在運行,並立即退出。

例如:如果你的程序是應用的主要實例並且當這個方法返回 true時,你應該繼續讓你的程序運行。 如果當它返回 false如果你的程序沒有取得鎖,它應該立刻退出,並且將參數發送給那個已經取到鎖的進程。

在 macOS 上, 當用戶嘗試在 Finder 中打開您的應用程序的第二個實例時, 系統會通過發出 open-fileopen-url 事件來自動強制執行單個實例,。 但是當用戶在命令行中啟動應用程序時, 系統的單實例機制將被繞過, 您必須手動調用此方法來確保單實例。

在第二個實例啟動時激活主實例窗口的示例:

const { app } = require('electron')
let myWindow = null

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 當運行第二個實例時,將會聚焦到myWindow這個窗口
    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore()
      myWindow.focus()
    }
  })

  // 創建 myWindow, 加載應用的其余部分, etc...
  app.whenReady().then(() => {
    myWindow = createWindow()
  })
}
復制

EN

app.hasSingleInstanceLock()

返回 Boolean

此方法返回你的應用實例當前是否持有單例鎖。 你可以通過 app.requestSingleInstanceLock()請求鎖,並且通過 app.releaseSingleInstanceLock() 釋放鎖。

EN

app.releaseSingleInstanceLock()

Releases all locks that were created by requestSingleInstanceLock. This will allow multiple instances of the application to once again run side by side.

EN

app.setUserActivity(type, userInfo[, webpageURL\]) macOS

  • type String - 活動的唯一標識。 映射到 NSUserActivity. activityType
  • userInfo any - App-specific state to store for use by another device.
  • webpageURL String (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be http or https.

創建一個 NSUserActivity 並將其設置為當前活動。 該活動之后可以Handoff到另一個設備。

EN

app.getCurrentActivityType() macOS

返回 String - 正在運行的 activity 的類型

EN

app.invalidateCurrentActivity() macOS

使當前的Handoff用戶活動無效。

EN

app.resignCurrentActivity() macOS

Marks the current Handoff user activity as inactive without invalidating it.

EN

app.updateCurrentActivity(type, userInfo) macOS

  • type String - 活動的唯一標識。 映射到 NSUserActivity. activityType
  • userInfo any - App-specific state to store for use by another device.

當其類型與 type 匹配時更新當前活動, 將項目從 用戶信息 合並到其當前 用戶信息 字典中。

EN

app.setAppUserModelId(id) Windows

  • id String

改變當前應用的 Application User Model IDid.

EN

app.setActivationPolicy(policy) macOS

  • policy String - Can be 'regular', 'accessory', or 'prohibited'.

Sets the activation policy for a given app.

Activation policy types:

  • 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface.
  • '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' - The application doesn’t appear in the Dock and may not create windows or be activated.

EN

app.importCertificate(options, callback) Linux

  •   選項
    

    對象

    • certificate String - pkcs12 文件的路徑
    • password String - 證書的密碼
  •   callback
    

    Function

    • result Integer - 導入結果

將 pkcs12 格式的證書導入到平台證書庫。 使用導入操作的 callback 調用返回 result ,值 0 表示成功,而任何其他值表示失敗,根據Chromium net_error_list

EN

app.disableHardwareAcceleration()

禁用當前應用程序的硬件加速。

這個方法只能在應用程序准備就緒(ready)之前調用。

EN

app.disableDomainBlockingFor3DAPIs()

By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior.

這個方法只能在應用程序准備就緒(ready)之前調用。

EN

app.getAppMetrics()

Returns ProcessMetric[\]: Array of ProcessMetric objects that correspond to memory and CPU usage statistics of all the processes associated with the app.

EN

app.getGPUFeatureStatus()

返回 GPUFeatureStatus-來自 chrome://gpu/ 的圖形功能狀態。

Note: This information is only usable after the gpu-info-update event is emitted.

EN

app.getGPUInfo(infoType)

  • infoType String - Can be basic or complete.

Returns Promise<unknown>

For infoType equal to complete: Promise is fulfilled with Object containing all the GPU Information as in chromium's GPUInfo object. 這包括 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'
}
復制

如果只需要基本信息,如vendorIddriverId,則應優先使用basic

EN

app.setBadgeCount(count) Linux**macOS

  • count Integer

返回 Boolean-是否成功調用。

設置當前應用程序的計數器標記. 將計數設置為 0 將隱藏該標記。

On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.

注意: Unity 啟動器依賴於 . desktop 文件, 獲取更多信息, 請閱讀 桌面環境集成

EN

app.getBadgeCount() Linux**macOS

Returns Integer - 獲取計數器提醒(badge) 中顯示的當前值

EN

app.isUnityRunning() Linux

Returns Boolean - 當前桌面環境是否為 Unity 啟動器

EN

app.getLoginItemSettings([options\]) macOS**Windows

  •   options
    

    Object (可選)

    • path String (optional) Windows - The executable path to compare against. Defaults to process.execPath.
    • args String[] (optional) Windows - The command-line arguments to compare against. Defaults to an empty array.

如果你為 app. setLoginItemSettings 提供pathargs 選項,那么你需要在這里為 openAtLogin 設置相同的參數已確保正確的設置。

返回 Object:

  • openAtLogin Boolean - true 如果應用程序設置為在登錄時打開, 則為 <0>true</0>

  • openAsHidden Boolean macOS - true if the app is set to open as hidden at login. 該配置在 MAS 構建 時不可用。

  • wasOpenedAtLogin Boolean macOS - true if the app was opened at login automatically. 該配置在 MAS 構建 時不可用。

  • wasOpenedAsHidden Boolean macOS - true if the app was opened as a hidden login item. 這表示應用程序在啟動時不應打開任何窗口。 該配置在 MAS 構建 時不可用。

  • restoreState Boolean macOS - true if the app was opened as a login item that should restore the state from the previous session. 這表示程序應該還原上次關閉時打開的窗口。 該配置在 MAS 構建 時不可用。

  • executableWillLaunchAtLogin Boolean Windows - true if app is set to open at login and its run key is not deactivated. This differs from openAtLogin as it ignores the args option, this property will be true if the given executable would be launched at login with any arguments.

  •   launchItems
    

    Object[]

    Windows

    • name String Windows - name value of a registry entry.
    • path String Windows - The executable to an app that corresponds to a registry entry.
    • args String[] Windows - the command-line arguments to pass to the executable.
    • scope String Windows - one of user or machine. Indicates whether the registry entry is under HKEY_CURRENT USER or HKEY_LOCAL_MACHINE.
    • enabled Boolean Windows - true if the app registry key is startup approved and therefore shows as enabled in Task Manager and Windows settings.

EN

app.setLoginItemSettings(settings) macOS**Windows

  •   settings
    

    Object

    • openAtLogin Boolean (optional) - true to open the app at login, false to remove the app as a login item. 默認值為 false.
    • openAsHidden Boolean (optional) macOS - true to open the app as hidden. 默認為false。 用戶可以從系統首選項中編輯此設置, 以便在打開應用程序時檢查 app.getLoginItemSettings().wasOpenedAsHidden 以了解當前值。 該配置在 MAS 構建 時不可用。
    • path String (optional) Windows - The executable to launch at login. Defaults to process.execPath.
    • args String[] (optional) Windows - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes.
    • enabled Boolean (optional) Windows - true will change the startup approved registry key and enable / disable the App in Task Manager and Windows Settings. 默認值為 true
    • name String (optional) Windows - value name to write into registry. Defaults to the app's AppUserModelId(). 設置應用程序的登錄項設置。

如果需要在使用Squirrel的 Windows 上使用 Electron 的 autoUpdater ,你需要將啟動路徑設置為 Update.exe,並傳遞指定應用程序名稱的參數。 例如:

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"`
  ]
})
復制

EN

app.isAccessibilitySupportEnabled() macOS**Windows

Returns Boolean - 如果開啟了Chrome的輔助功能, 則返回 true,其他情況返false。 如果使用了輔助技術(例如屏幕閱讀),該 API 將返回 `true</0。 查看更多細節,請查閱 chromium.org/developers/design-documents/accessibility

app.setAccessibilitySupportEnabled(enabled) macOS Windows`

enable 邏輯值 - 啟用或禁用訪問權限樹視圖。手動啟用 Chrome 的輔助功能的支持, 允許在應用程序中設置是否開啟輔助功能。 在Chromium's accessibility docs查看更多的細節 默認為禁用此 API 必須在 ready 事件觸發后調用**注意:** 渲染進程樹會明顯的影響應用的性能。默認情況下不應該啟用。

EN

app.showAboutPanel()

Show the app's about panel options. These options can be overridden with app.setAboutPanelOptions(options).

EN

app.setAboutPanelOptions(options)

  •   選項
    

    對象

    • applicationName String (可選) - 應用程序的名字
    • applicationVersion String (可選) - 應用程序版本
    • copyright String (可選) - 版權信息
    • version String (optional) macOS - The app's build version number.
    • credits String (optional) macOS Windows - Credit information.
    • authors String[] (optional) Linux - List of app authors.
    • website String (optional) Linux - The app's website.
    • iconPath String (optional) Linux Windows - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.

設置 "關於" 面板選項。 This will override the values defined in the app's .plist file on macOS. 更多詳細信息, 請查閱 Apple 文檔 。 在 Linux 上,沒有默認值,所以必須設置值才能顯示。

If you do not set credits but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple documentation for more information.

EN

app.isEmojiPanelSupported()

返回 布爾值 - 當前操作系統版本是否允許使用本機emoji選取器。

EN

app.showEmojiPanel() macOS**Windows

打開系統自身的emjio選取器。

EN

app.startAccessingSecurityScopedResource(bookmarkData) mas

  • bookmarkData String - base64 編碼的安全作用域的書簽數據(bookmark data) ,通過 dialog.showOpenDialog 或者 dialog.showSaveDialog 方法獲取。

返回 Function - 該函數 必須 在你完成訪問安全作用域文件后調用一次。 如果你忘記停止訪問書簽,內核資源將會泄漏,並且你的應用將失去完全到達沙盒之外的能力,直到應用重啟。

//開始讀取文件
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data)
// You can now access the file outside of the sandbox 🎉

// Remember to stop accessing the file once you've finished with it.
stopAccessingSecurityScopedResource()
復制

開始訪問安全范圍內的資源。 通過這個方法,Electron 應用被打包為可到達Mac App Store沙箱之外訪問用戶選擇的文件。 關於系統工作原理,請查閱Apple's documentation

EN

app.enableSandbox()

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.

這個方法只能在應用程序准備就緒(ready)之前調用。

EN

app.isInApplicationsFolder() macOS

Returns Boolean - Whether the application is currently running from the systems Application folder. Use in combination with app.moveToApplicationsFolder()

EN

app.moveToApplicationsFolder([options\]) macOS

  •   options
    

    Object (可選)

    • conflictHandler Function\ (optional) - A handler for potential conflict in move failure.conflictType String - The type of move conflict encountered by the handler; can be exists or existsAndRunning, where exists means that an app of the same name is present in the Applications directory and existsAndRunning means both that it exists and that it's presently running.

Returns Boolean - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch.

No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the dialog API.

注意:如果並非是用戶造成操作失敗,這個方法會拋出錯誤。 例如,如果用戶取消了授權會話,這個方法將返回false。 如果無法執行復制操作, 則此方法將拋出錯誤。 The message in the error should be informative and tell you exactly what went wrong.

By default, if an app of the same name as the one being moved exists in the Applications directory and is not running, the existing app will be trashed and the active app moved into its place. If it is running, the pre-existing running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning false will ensure no further action is taken, returning true will result in the default behavior and the method continuing.

例如:

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.

EN

app.isSecureKeyboardEntryEnabled() macOS

Returns Boolean - whether Secure Keyboard Entry is enabled.

By default this API will return false.

EN

app.setSecureKeyboardEntryEnabled(enabled) macOS

  • enabled Boolean - Enable or disable Secure Keyboard Entry

Set the Secure Keyboard Entry is enabled in your application.

By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.

See Apple's documentation for more details.

Note: Enable Secure Keyboard Entry only when it is needed and disable it when it is no longer needed.

EN

屬性

EN

app.accessibilitySupportEnabled macOS**Windows

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.

See Chromium's accessibility docs for more details. 默認為禁用

此 API 必須在 ready 事件觸發后調用

注意: 渲染進程樹會明顯的影響應用的性能。默認情況下不應該啟用。

EN

app.applicationMenu

A Menu | null property that returns Menu if one has been set and null otherwise. Users can pass a Menu to set this property.

EN

app.badgeCount Linux**macOS

An Integer property that returns the badge count for current app. Setting the count to 0 will hide the badge.

On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher.

注意: Unity 啟動器依賴於 . desktop 文件, 獲取更多信息, 請閱讀 桌面環境集成

Note: On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect.

EN

app.commandLine Readonly

A CommandLine object that allows you to read and manipulate the command line arguments that Chromium uses.

EN

app.dock macOS**Readonly

A Dock | undefined object that allows you to perform actions on your app icon in the user's dock on macOS.

EN

app.isPackaged Readonly

返回一個Boolean值,如果應用已經打包,返回true ,否則返回false 。 對於大多數應用程序,此屬性可用於區分開發和生產環境。

EN

app.name

A String property that indicates the current application's name, which is the name in the application's package.json file.

Usually the name field of package.json is a short lowercase name, according to the npm modules spec. 通常還應該指定一個 productName 字段, 是首字母大寫的完整名稱,用於表示應用程序的名稱。Electron 會優先使用這個字段作為應用名。

EN

app.userAgentFallback

A String which is the user agent string Electron will use as a global fallback.

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.

EN

app.allowRendererProcessReuse

A Boolean which when true disables the overrides that Electron has in place to ensure renderer processes are restarted on every navigation. The current default value for this property is true.

The intention is for these overrides to become disabled by default and then at some point in the future this property will be removed. This property impacts which native modules you can use in the renderer process. For more information on the direction Electron is going with renderer process restarts and usage of native modules in the renderer process please check out this Tracking Issue.

EN

app.runningUnderRosettaTranslation macOS**Readonly

A Boolean which when true indicates that the app is currently running under the Rosetta Translator Environment.

You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM