app | Electron
https://www.electronjs.org/pt/docs/latest/api/app • 291 KB fetched
Open original page
app | Electron
Ir para o conteúdo principal
Electron Documentação API Blog Ferramentas
* Electron Forge
* Electron Fiddle
Comunidade
* Governança
* Vitrine
* Recursos
Versões Português
* English
* Deutsch
* Español
* Français
* 日本語
* Português
* Русский
* 中文
Pesquisar
* Módulos do Processo Principais
* app
* autoUpdater
* BaseWindow
* BrowserView
* Deprecated
* BrowserWindow
* clipboard
* contentTracing
* crashReporter
* desktopCapturer
* dialog
* globalShortcut
* ImageView
* inAppPurchase
* ipcMain
* Menu
* MenuItem
* MessageChannelMain
* MessagePortMain
* nativeImage
* nativeTheme
* net
* netLog
* Notificação
* powerMonitor
* powerSaveBlocker
* process
* protocol
* pushNotifications
* safeStorage
* screen
* session
* sharedTexture
* ShareMenu
* shell
* systemPreferences
* TouchBar
* Tray
* utilityProcess
* webContents
* WebContentsView
* webFrameMain
* Exibir
* Módulos do Processo de Renderização
* Utility Process Modules
* Elementos de DOM Personalizado
* Chromium e Node.js
* Classes
* Estruturas da API
*
* Módulos do Processo Principais
* app Nesta página
app
Controle o ciclo de vida de eventos da sua aplicação.
Process: Main
O seguinte exemplo mostra como encerrar a aplicação quando a última janela é fechada:
const { app } = require ( 'electron' )
app . on ( 'window-all-closed' , ( ) => {
app . quit ( )
} )
Eventos
O objeto app emite os seguintes eventos:
Evento: 'will-finish-launching'
Emitido quando a aplicação termina inicialização básica. No Windows e Linux o evento will-finish-launching é o mesmo que o evento ready ; no macOS, este evento representa a notificação applicationWillFinishLaunching de NSApplication .
Na maioria dos casos, você deve fazer tudo no manipulador do evento ready .
Evento: 'ready'
Retorna:
* event Event
* launchInfo Record<string, any> | NotificationResponse macOS
Emitido uma vez, quando o Electron terminou de inicializar. No macOS, launchInfo contém a userInfo do NSUserNotification ou as informações de UNNotificationResponse que foi usado para abrir o aplicativo, se foi lançado pelo Centro de Notificações. Você também pode chamar app.isReady() para verificar se este evento já foi acionado e app.whenReady() para obter uma Promise que é cumprida quando o Electron é inicializado.
[!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.
Evento: 'window-all-closed'
Emitido quando todas as janelas foram fechadas.
Se você não escutar esse evento e todas as janelas forem fechadas, o comportamento padrão é fechar a aplicação. No entanto, se você estiver escutando, você controla se a aplicação fecha ou não. Se o usuário pressionou Cmd + Q ou o desenvolvedor chamou app.quit() , o Electron irá primeiro tentar fechar todas as janelas e então emitir o evento will-quit e neste caso, window-all-closed não será emitido.
Evento: 'before-quit'
Retorna:
* event Event
Emitido antes da aplicação começar a fechar suas janelas. Chamar o event.preventDefault() vai previnir o comportamento padrão, que é encerrar o aplicativo.
[!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] On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
Evento: 'will-quit'
Retorna:
* event Event
Emitido quando todas as janelas forem fechadas e o aplicativo será encerrado. Chamar o event.preventDefault() vai previnir o comportamento padrão, que é encerrar o aplicativo.
Consulte a descrição do evento window-all-closed para as diferenças entre os eventos will-quit e window-all-closed .
[!NOTE] On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
Evento: 'quit'
Retorna:
* event Event
* exitCode Integer
Emitido quando a aplicação esta sendo encerrada(quitting).
[!NOTE] On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.
Evento: 'open-file' macOS
Retorna:
* event Event
* path string
Emitido quando o usuário deseja abrir um arquivo com a aplicação. O evento open-file geralmente é emitido quando a aplicação já está aberta e o SO deseja reutilizar a aplicação para abrir o arquivo. open-file também é emitido quando um arquivo é solto sobre o dock e a aplicação ainda não está em execução. Certifique-se que o evento open-file seja detectado desde o início da aplicação para manipulá-lo (inclusive antes do evento ready ser emitido).
Se você deseja manipular esse evento, você deve chamar event.preventDefault() .
No Windows, você tem que analisar process.argv (no processo principal) para obter o filepath.
Evento: 'open-url' macOS
Retorna:
* event Event
* string url
Emitido quando o usuário deseja abrir um URL com a aplicação. Your application's Info.plist file must define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication .
As with the open-file event, be sure to register a listener for the open-url event early in your application startup to detect if the application is being opened to handle a URL. If you register the listener in response to a ready event, you'll miss URLs that trigger the launch of your application.
Evento: 'activate' macOS
Retorna:
* event Event
* hasVisibleWindows boolean
Emitido quando a aplicação é ativada. Várias ações podem disparar esse evento, tais como iniciando o aplicativo pela primeira vez, a tentativa de re-iniciar o aplicativo quando ele já está sendo executado, ou clicando no ícone de barra de tarefas ou doca do aplicativo.
Evento: 'did-become-active' macOS
Retorna:
* event Event
Emitted when the application becomes active. This differs from the activate event in that did-become-active is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. It is also emitted when a user switches to the app via the macOS App Switcher.
Event: 'did-resign-active' macOS
Retorna:
* event Event
Emitted when the app is no longer active and doesn’t have focus. This can be triggered, for example, by clicking on another application or by using the macOS App Switcher to switch to another application.
Event: 'continue-activity' macOS
Retorna:
* event Event
* type string - A string identifying the activity. Maps to NSUserActivity.activityType .
* userInfo unknown - Contains app-specific state stored by the activity on another device.
* Objeto details
* webpageURL string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available.
Emitted during Handoff when an activity from a different device wants to be resumed. Você deve chamar event.preventDefault() caso queira manipular esse evento.
Uma atividade do usuário pode ser continuada apenas em uma aplicação que tem o mesmo Team ID do desenvolvedor como o aplicativo fonte da atividade e que suporta o tipo da atividade. Tipos de atividade suportadas são especificadas no Info.plist do aplicativo sob a chave NSUserActivityTypes .
Event: 'will-continue-activity' macOS
Retorna:
* event Event
* type string - A string identifying the activity. Maps to NSUserActivity.activityType .
Emitted during Handoff before an activity from a different device wants to be resumed. Você deve chamar event.preventDefault() caso queira manipular esse evento.
Event: 'continue-activity-error' macOS
Retorna:
* event Event
* type string - A string identifying the activity. Maps to NSUserActivity.activityType .
* error string - A string with the error's localized description.
Emitted during Handoff when an activity from a different device fails to be resumed.
Event: 'activity-was-continued' macOS
Retorna:
* event Event
* type string - A string identifying the activity. Maps to NSUserActivity.activityType .
* userInfo unknown - Contains app-specific state stored by the activity.
Emitted during Handoff after an activity from this device was successfully resumed on another one.
Event: 'update-activity-state' macOS
Retorna:
* event Event
* type string - A string identifying the activity. Maps to NSUserActivity.activityType .
* userInfo unknown - Contains app-specific state stored by the activity.
Emitted when Handoff is about to be resumed on another device. If you need to update the state to be transferred, you should call event.preventDefault() immediately, construct a new userInfo dictionary and call app.updateCurrentActivity() in a timely manner. Caso contrário, a operação irá falhar e continue-activity-error será chamado.
Evento: 'new-window-for-tab' macOS
Retorna:
* 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 .
You must create a window in this handler in order for macOS tabbing to work as expected.
Evento: 'browser-window-blur'
Retorna:
* event Event
* window BrowserWindow
Emitted when a browserWindow gets blurred.
Evento: 'browser-window-focus'
Retorna:
* event Event
* window BrowserWindow
Emitted when a browserWindow gets focused.
Evento: 'browser-window-created'
Retorna:
* event Event
* window BrowserWindow
Emitted when a new browserWindow is created.
Evento: 'web-contents-created'
Retorna:
* event Event
* webContents WebContents
Emitted when a new webContents is created.
Evento: 'certificate-error'
Retorna:
* event Event
* webContents WebContents
* string url
* error string - The error code
* certificate Certificate
* callback Function
* isTrusted boolean - Whether to consider the certificate as trusted
* isMainFrame boolean
Emitido quando a verificação do certificate para o url falha, para confiar no certificado você deve prevenir o comportamento padrão com event.preventDefault() e chamar callback(true) .
const { app } = require ( 'electron' )
app . on ( 'certificate-error' , ( event , webContents , url , error , certificate , callback ) => {
if ( url === 'https://github.com' ) {
// Lógica de verificação.
event . preventDefault ( )
callback ( true )
} else {
callback ( false )
}
} )
Evento: 'select-client-certificate'
Retorna:
* event Event
* webContents WebContents
* url URL
* certificateList Certificate[]
* callback Function
* certificate Certificate (optional)
Emitido quando um certificado de cliente é solicitado.
O url corresponde à entrada de navegação solicitando o certificado do cliente e callback pode ser chamado com uma entrada filtrada da lista. Usar event.preventDefault() previne a aplicação de utilizar o primeiro certificado da store.
const { app } = require ( 'electron' )
app . on ( 'select-client-certificate' , ( event , webContents , url , list , callback ) => {
event . preventDefault ( )
callback ( list [ 0 ] )
} )
Evento: 'login'
Retorna:
* event Event
* webContents WebContents (optional)
* authenticationResponseDetails Object
* url URL
* pid number
* isRequestForNavigation boolean - Indicates whether the request is for a navigation.
* firstAuthAttempt boolean - Indicates whether this is the first authentication attempt.
* responseHeaders Record<string, string | string[]> (optional) - The headers returned in the response.
* Objeto authInfo
* isProxy boolean
* scheme string
* host string
* port Integer
* realm string
* callback Function
* username string (optional)
* password string (optional)
Emitted when webContents or Utility process wants to do basic auth.
O comportamento padrão é cancelar todas as autenticações. Para sobrescrever isso você deve prevenir o comportamento padrão com event.preventDefault() e chamar o callback(username, password) com as credenciais.
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.
Event: 'gpu-info-update'
Emitted whenever there is a GPU info update.
Event: 'render-process-gone'
Retorna:
* event Event
* webContents WebContents
* details RenderProcessGoneDetails
Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
Event: 'child-process-gone'
Retorna:
* event Event
* Objeto details
* type string - Process type. Um dos seguintes valores:
* Utilidade
* Zygote
* Ajuda ao Sandbox
* GPU
* Pepper Plugin
* Pepper Plugin Broker
* Desconhecido
* reason string - The reason the child process is gone. Valores possíveis:
* 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
* memory-eviction - Process proactively terminated to prevent a future out-of-memory (OOM) situation
* exitCode number - The exit code for the process (e.g. status from waitpid if on POSIX, from GetExitCodeProcess on Windows).
* serviceName string (optional) - The non-localized name of the process.
* name string (optional) - The name of the process. Exemplos para utilidade: 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.
Event: 'accessibility-support-changed' no macOS e no Windows
Retorna:
* event Event
* accessibilitySupportEnabled boolean - true when Chromium's accessibility support is enabled, false otherwise.
Emitted when Chromium's accessibility support changes. Este evento é acionado quando a tecnologias assistivas, tais como leitores de tela, estão habilitadas ou desabilitadas. Veja https://www.chromium.org/developers/design-documents/accessibility para mais detalhes.
Evento: 'session-created'
Retorna:
* session Session
Emitido quando Electron criar uma nova session .
const { app } = require ( 'electron' )
app . on ( 'session-created' , ( session ) => {
console . log ( session )
} )
Evento: 'second-instance'
Retorna:
* event Event
* argv string[] - Um array dos argumentos da linha de comando da segunda instância
* workingDirectory string - O diretório de trabalho da segunda instância
* additionalData unknown - A JSON object of additional data passed from the second instance
This event will be emitted inside the primary instance of your application when a second instance has been executed and calls app.requestSingleInstanceLock() .
argv is an Array of the second instance's command line arguments, and workingDirectory is its current working directory. Geralmente, aplicativos reagem a isso tornando a janela principal deles visível e em primeiro plano.
note
argv will not be exactly the same list of arguments as those passed to the second instance. The order might change and additional arguments might be appended. If you need to maintain the exact same arguments, it's advised to use additionalData instead.
[!NOTE] If the second instance is started by a different user than the first, the argv array will not include the arguments.
Esse evento é garantido que será emitido após o evento ready do objeto app ser emitido.
[!NOTE] Extra command line arguments might be added by Chromium, such as --original-process-start-time .
Métodos
O objeto app tem os seguintes métodos:
[!NOTE] Some methods are only available on specific operating systems and are labeled as such.
app.quit()
Tenta fechar todas as janelas. O evento before-quit será emitido primeiro. Se todas as janelas forem fechadas com sucesso, o evento will-quit será emitido e por padrão, e o aplicativo será encerrado.
Este método garante que todos os manipuladores de vento beforeunload e unload seja executados corretamente. É possível que a janela cancele, retornando false no manipulador de eventos beforeunload .
app.exit([exitCode])
* exitCode Integer (opcional)
Exits immediately with exitCode . exitCode defaults to 0.
All windows will be closed immediately without asking the user, and the before-quit and will-quit events will not be emitted.
app.relaunch([options])
* Objeto options (opcional)
* args string[] (opcional)
* execPath string (opcional)
Relaunches the app when the current instance exits.
By default, the new instance will use the same working directory and command line arguments as the current instance. When args is specified, the args will be passed as the command line arguments instead. When execPath is specified, the execPath will be executed for the relaunch instead of the current app.
Note that this method does not quit the app when executed. You have to call app.quit or app.exit after calling app.relaunch to make the app restart.
When app.relaunch is called multiple times, multiple instances will be started after the current instance exits.
An example of restarting the current instance immediately and adding a new command line argument to the new instance:
const { app } = require ( 'electron' )
app . relaunch ( { args : process . argv . slice ( 1 ) . concat ( [ '--relaunch' ] ) } )
app . exit ( 0 )
app.isReady()
Retorna boolean - true se o Electron tiver inicializado, false caso contrário. See also app.whenReady() .
app.whenReady()
Retorna Promise<void> - cumprido quando o Electron é inicializado. Pode ser usado como uma al
Links found on this page
- Ir para o conteúdo principal [direct]
- Electron [direct]
- Documentação [direct]
- Blog [direct]
- Electron Forge [direct]
- Electron Fiddle [direct]
- Governança [direct]
- Vitrine [direct]
- Recursos [direct]
- Versões [direct]
- English [direct]
- Deutsch [direct]
- Español [direct]
- Français [direct]
- 日本語 [direct]
- Русский [direct]
- 中文 [direct]
- autoUpdater [direct]
- BaseWindow [direct]
- BrowserView Deprecated [direct]
- BrowserWindow [direct]
- clipboard [direct]
- contentTracing [direct]
- crashReporter [direct]
- desktopCapturer [direct]
- dialog [direct]
- globalShortcut [direct]
- ImageView [direct]
- inAppPurchase [direct]
- ipcMain [direct]
- Menu [direct]
- MenuItem [direct]
- MessageChannelMain [direct]
- MessagePortMain [direct]
- nativeImage [direct]
- nativeTheme [direct]
- net [direct]
- netLog [direct]
- Notificação [direct]
- powerMonitor [direct]
- powerSaveBlocker [direct]
- process [direct]
- protocol [direct]
- pushNotifications [direct]
- safeStorage [direct]
- screen [direct]
- session [direct]
- sharedTexture [direct]
- ShareMenu [direct]
- shell [direct]
- systemPreferences [direct]
- TouchBar [direct]
- Tray [direct]
- utilityProcess [direct]
- webContents [direct]
- WebContentsView [direct]
- webFrameMain [direct]
- Exibir [direct]
- Elementos de DOM Personalizado [direct]
- Chromium e Node.js [direct]
- Classes [direct]
- Estruturas da API [direct]
- Main [direct]
- NotificationResponse [direct]
- NSUserNotification [direct]
- UNNotificationResponse [direct]
- NSUserActivity.activityType [direct]
- Handoff [direct]
- Certificate [direct]
- RenderProcessGoneDetails [direct]
- https://www.chromium.org/developers/design-documents/accessibility [direct]
- .desktop filename [direct]
- here [direct]
- ISO 3166 [direct]
- Electron Forge [direct]
- Electron Packager [direct]
- Apple's documentation [direct]
- declare the protocol in your manifest [direct]
- Apple's documentation [direct]
- Task[] [direct]