Exibe diálogos nativos do sistema para abrir e salvar arquivos, alertas, etc.
Process: Main
An example of showing a dialog to select multiple files:
const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
Métodos
O módulo dialog possúi os seguintes métodos:
dialog.showOpenDialogSync([window, ]options[, callback)
- windowBaseWindow (optional)
- optionsObject- 
- titlestring (opcional)
- defaultPathstring (opcional)
- buttonLabelstring (opcional) - Rótulo personalizado para o botão de confirmação, quando deixado em branco o label padrão será usado.
- filtersFileFilter[] (optional)
- propertiesstring[] (optional) - Contains which features the dialog should use. The following values are supported:- 
- openFile- Permite selecionar arquivos.
- openDirectory- Permite selecionar diretórios.
- multiSelections- Permite selecionar múltiplos caminhos.
- showHiddenFiles- Mostra arquivos escondidos no dialog.
- createDirectorymacOS - Allow creating new directories from dialog.
- promptToCreateWindows - Prompt for creation if the file path entered in the dialog does not exist. Na verdade este valor não cria o arquivo no caminho especificado mas permite que o aplicativo entenda que deverá criar o diretório não existente.
- noResolveAliasesmacOS - Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path.
- treatPackageAsDirectorymacOS - Treat packages, such as- .appfolders, as a directory instead of a file.
- dontAddToRecentWindows - Do not add the item being opened to the recent documents list.
 
- messagestring (opcional) macOS - Mensagem a ser apresentada acima da janela de entrada.
- securityScopedBookmarksboolean (optional) macOS MAS - Create security scoped bookmarks when packaged for the Mac App Store.
 
Returns string[] | undefined, the file paths chosen by the user; if the dialog is cancelled it returns undefined.
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal.
The filters specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. Como por exemplo:
{
  filters: [
    { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
    { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
    { name: 'Custom File Type', extensions: ['as'] },
    { name: 'All Files', extensions: ['*'] }
  ]
}
As array de extensions devem conter extensões sem caracteres-curinga ou pontos. ('png' é bom mas, '.png' e '*.png' são ruins). Para mostrar todos os arquivos use o caracter-curinga * (nenhum ouro caracter-curinga é suportado).
[!NOTE] On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.
dialog.showOpenDialogSync(mainWindow, {
  properties: ['openFile', 'openDirectory']
})
[!NOTE] On Linux defaultPath is not supported when using portal file chooser dialogs unless the portal backend is version 4 or higher. You can use --xdg-portal-required-version command-line switch to force gtk or kde dialogs.
dialog.showOpenDialog([window, ]options)
- windowBaseWindow (optional)
- optionsObject- 
- titlestring (opcional)
- defaultPathstring (opcional)
- buttonLabelstring (opcional) - Rótulo personalizado para o botão de confirmação, quando deixado em branco o label padrão será usado.
- filtersFileFilter[] (optional)
- propertiesstring[] (optional) - Contains which features the dialog should use. The following values are supported:- 
- openFile- Permite selecionar arquivos.
- openDirectory- Permite selecionar diretórios.
- multiSelections- Permite selecionar múltiplos caminhos.
- showHiddenFiles- Mostra arquivos escondidos no dialog.
- createDirectorymacOS - Allow creating new directories from dialog.
- promptToCreateWindows - Prompt for creation if the file path entered in the dialog does not exist. Na verdade este valor não cria o arquivo no caminho especificado mas permite que o aplicativo entenda que deverá criar o diretório não existente.
- noResolveAliasesmacOS - Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path.
- treatPackageAsDirectorymacOS - Treat packages, such as- .appfolders, as a directory instead of a file.
- dontAddToRecentWindows - Do not add the item being opened to the recent documents list.
 
- messagestring (opcional) macOS - Mensagem a ser apresentada acima da janela de entrada.
- securityScopedBookmarksboolean (optional) macOS MAS - Create security scoped bookmarks when packaged for the Mac App Store.
 
Returns Promise<Object> - Resolve with an object containing the following:
- canceledboolean - whether or not the dialog was canceled.
- filePathsstring[] - Um array de caminhos de arquivos selecionados pelo usuário. If the dialog is cancelled this will be an empty array.
- bookmarksstring[] (optional) macOS MAS - An array matching the- filePathsarray of base64 encoded strings which contains security scoped bookmark data.- securityScopedBookmarksmust be enabled for this to be populated. (For return values, see table here.)
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal.
The filters specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. Como por exemplo:
{
  filters: [
    { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
    { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
    { name: 'Custom File Type', extensions: ['as'] },
    { name: 'All Files', extensions: ['*'] }
  ]
}
As array de extensions devem conter extensões sem caracteres-curinga ou pontos. ('png' é bom mas, '.png' e '*.png' são ruins). Para mostrar todos os arquivos use o caracter-curinga * (nenhum ouro caracter-curinga é suportado).
[!NOTE] On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.
dialog.showOpenDialog(mainWindow, {
  properties: ['openFile', 'openDirectory']
}).then(result => {
  console.log(result.canceled)
  console.log(result.filePaths)
}).catch(err => {
  console.log(err)
})
[!NOTE] On Linux defaultPath is not supported when using portal file chooser dialogs unless the portal backend is version 4 or higher. You can use --xdg-portal-required-version command-line switch to force gtk or kde dialogs.
dialog.showSaveDialogSync([window, ]options)
- windowBaseWindow (optional)
- optionsObject- 
- titlestring (optional) - The dialog title. Cannot be displayed on some Linux desktop environments.
- defaultPathstring (opcional) - Caminho absoluto do diretório, caminho absoluto do arquivo, ou o nome do arquivo a ser usado como padrão.
- buttonLabelstring (opcional) - Rótulo personalizado para o botão de confirmação, quando deixado em branco o label padrão será usado.
- filtersFileFilter[] (optional)
- messagestring (opcional) macOS - Mensagem a ser exibida acima de campos de texto.
- nameFieldLabelstring (opcional) macOS - Rótulo personalizado do texto a ser exibido em frente ao campo do nome do arquivo.
- showsTagFieldboolean (opcional) macOS - apresenta a tag do campo de entrada, por padrão- true.
- propertiesstring[] (optional)- 
- showHiddenFiles- Mostra arquivos escondidos no dialog.
- createDirectorymacOS - Allow creating new directories from dialog.
- treatPackageAsDirectorymacOS - Treat packages, such as- .appfolders, as a directory instead of a file.
- showOverwriteConfirmationLinux - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
- dontAddToRecentWindows - Do not add the item being saved to the recent documents list.
 
- securityScopedBookmarksboolean (optional) macOS MAS - Create a security scoped bookmark when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path.
 
Returns string, the path of the file chosen by the user; if the dialog is cancelled it returns an empty string.
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal.
Os filters especificam um array de tipos de arquivo que podem ser exibidos, veja dialog.ShowOpenDialog para exemplos.
dialog.showSaveDialog([window, ]options)
- windowBaseWindow (optional)
- optionsObject- 
- titlestring (optional) - The dialog title. Cannot be displayed on some Linux desktop environments.
- defaultPathstring (opcional) - Caminho absoluto do diretório, caminho absoluto do arquivo, ou o nome do arquivo a ser usado como padrão.
- buttonLabelstring (opcional) - Rótulo personalizado para o botão de confirmação, quando deixado em branco o label padrão será usado.
- filtersFileFilter[] (optional)
- messagestring (opcional) macOS - Mensagem a ser exibida acima de campos de texto.
- nameFieldLabelstring (opcional) macOS - Rótulo personalizado do texto a ser exibido em frente ao campo do nome do arquivo.
- showsTagFieldboolean (optional) macOS - Show the tags input box, defaults to- true.
- propertiesstring[] (optional)- 
- showHiddenFiles- Mostra arquivos escondidos no dialog.
- createDirectorymacOS - Allow creating new directories from dialog.
- treatPackageAsDirectorymacOS - Treat packages, such as- .appfolders, as a directory instead of a file.
- showOverwriteConfirmationLinux - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
- dontAddToRecentWindows - Do not add the item being saved to the recent documents list.
 
- securityScopedBookmarksboolean (optional) macOS MAS - Create a security scoped bookmark when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path.
 
Returns Promise<Object> - Resolve with an object containing the following:
- canceledboolean - whether or not the dialog was canceled.
- filePathstring - If the dialog is canceled, this will be an empty string.
- bookmarkstring (optional) macOS MAS - Base64 encoded string which contains the security scoped bookmark data for the saved file.- securityScopedBookmarksmust be enabled for this to be present. (For return values, see table here.)
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal.
Os filters especificam um array de tipos de arquivo que podem ser exibidos, veja dialog.ShowOpenDialog para exemplos.
[!NOTE] On macOS, using the asynchronous version is recommended to avoid issues when expanding and collapsing the dialog.
dialog.showMessageBoxSync([window, ]options)
- windowBaseWindow (optional)
- optionsObject- 
- messagestring - Conteúdo da caixa de mensagem.
- typestring (opcional) - Pode ser- none,- info,- error,- questionou- warning. No Windows,- questionexibe o mesmo ícone que- info, a menos que você especifique um ícone usando a opção- icon. No macOS, tanto- warningcomo- errorexibirão o mesmo ícone de alerta.
- buttonsstring[] (optional) - Array of texts for buttons. On Windows, an empty array will result in one button labeled "OK".
- defaultIdInteger (opcional) - Indicador do botão na array de botões que será selecionado como padrão quando a caixa de mensagem abrir.
- titlestring (opcional) - Título da caixa de mensagem, algumas plataformas não o exibirão.
- detailstring (opcional) - Informações adicionais da mensagem.
- icon(NativeImage | string) (optional)
- textWidthInteger (optional) macOS - Custom width of the text in the message box.
- cancelIdInteger (opcional) - O indicador do botão será usado para cancelar o diálogo, por via da tecla- Esc. Por padrão é atribuído ao primeiro botão como "cancelar" ou "não" como rótulos. If no such labeled buttons exist and this option is not set,- 0will be used as the return value.
- noLinkboolean (opcional) - No Windows, o Electron tentará identificar qual dos- buttonssão botões comuns (como "cancelar" ou "sim"), e exibir os outros como links de comandos no diálogo. Ele pode fazer o diálogo ser apresentado com o estilo dos aplicativos modernos do Windows. Se você não deseja esse comportamento, você pode definir- noLinkpara- true.
- normalizeAccessKeysboolean (opcional) - Normaliza o acesso às teclas do teclado entre as plataformas. Por padrão é- false. Ativando-o assume-se que- &é usado nos rótulos dos botões para atribuir a tecla de atalho de acesso do teclado assim os rótulos serão convertidos para que funcionem corretamente em cada plataforma, os caracteres- &são removidos no macOS, convertidos para- _no Linux, e deixados intactos no Windows. Por exemplo, um rótulo de botão- Vie&wserá convertido para- Vie_wno Linux e- Viewno macOS e pode ser selecionado através de- Alt-Wno Windows e Linux.
 
Returns Integer - the index of the clicked button.
Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button.
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal. If window is not shown dialog will not be attached to it. In such case it will be displayed as an independent window.
dialog.showMessageBox([window, ]options)
- windowBaseWindow (optional)
- optionsObject- 
- messagestring - Conteúdo da caixa de mensagem.
- typestring (opcional) - Pode ser- none,- info,- error,- questionou- warning. No Windows,- questionexibe o mesmo ícone que- info, a menos que você especifique um ícone usando a opção- icon. No macOS, tanto- warningcomo- errorexibirão o mesmo ícone de alerta.
- buttonsstring[] (optional) - Array of texts for buttons. On Windows, an empty array will result in one button labeled "OK".
- defaultIdInteger (opcional) - Indicador do botão na array de botões que será selecionado como padrão quando a caixa de mensagem abrir.
- signalAbortSignal (optional) - Pass an instance of AbortSignal to optionally close the message box, the message box will behave as if it was cancelled by the user. On macOS,- signaldoes not work with message boxes that do not have a parent window, since those message boxes run synchronously due to platform limitations.
- titlestring (opcional) - Título da caixa de mensagem, algumas plataformas não o exibirão.
- detailstring (opcional) - Informações adicionais da mensagem.
- checkboxLabelstring (optional) - If provided, the message box will include a checkbox with the given label.
- checkboxCheckedboolean (optional) - Initial checked state of the checkbox.- falseby default.
- icon(NativeImage | string) (optional)
- textWidthInteger (optional) macOS - Custom width of the text in the message box.
- cancelIdInteger (opcional) - O indicador do botão será usado para cancelar o diálogo, por via da tecla- Esc. Por padrão é atribuído ao primeiro botão como "cancelar" ou "não" como rótulos. If no such labeled buttons exist and this option is not set,- 0will be used as the return value.
- noLinkboolean (opcional) - No Windows, o Electron tentará identificar qual dos- buttonssão botões comuns (como "cancelar" ou "sim"), e exibir os outros como links de comandos no diálogo. Ele pode fazer o diálogo ser apresentado com o estilo dos aplicativos modernos do Windows. Se você não deseja esse comportamento, você pode definir- noLinkpara- true.
- normalizeAccessKeysboolean (opcional) - Normaliza o acesso às teclas do teclado entre as plataformas. Por padrão é- false. Ativando-o assume-se que- &é usado nos rótulos dos botões para atribuir a tecla de atalho de acesso do teclado assim os rótulos serão convertidos para que funcionem corretamente em cada plataforma, os caracteres- &são removidos no macOS, convertidos para- _no Linux, e deixados intactos no Windows. Por exemplo, um rótulo de botão- Vie&wserá convertido para- Vie_wno Linux e- Viewno macOS e pode ser selecionado através de- Alt-Wno Windows e Linux.
 
Returns Promise<Object> - resolves with a promise containing the following properties:
- responsenumber - The index of the clicked button.
- checkboxCheckedboolean - The checked state of the checkbox if- checkboxLabelwas set. Otherwise- false.
Shows a message box.
O argumento window permite que o diálogo seja acoplado a janela parent, tornando-a modal.
dialog.showErrorBox(title, content)
- titlestring - O título a ser exibido na caixa de erro.
- contentstring - O conteúdo a ser exibido na caixa de erro.
Exibe um dialog modal que apresenta uma mensagem de erro.
Esse API pode ser chamado com segurança antes de que o evento ready que é emitido pelo app, é usado para reportar erros nos estágios iniciais da execução do aplicativo. Se chamado antes do evento ready do aplicativo no Linux, a mensagem será emitida para stderr, e o GUI do dialog não será mostrado.
dialog.showCertificateTrustDialog([window, ]options) macOS Windows
- windowBaseWindow (optional)
- optionsObject- 
- certificateCertificate - The certificate to trust/import.
- messagestring - A mensagem a ser exibida para o usuário.
 
Returns Promise<void> - resolves when the certificate trust dialog is shown.
No macOS, esse método exibe um dialog modal que apresenta uma mensagem e informação de certificado, dando ao usuário a opção de confiar/importar o certificado. Se você fornecer um argumento window o dialog será acoplado à janela parent, fazendo-a modal.
No Windows as opções são mais limitadas, devido às API's do Win32 usadas:
- Como o macOS fornece o seu próprio diálogo de confirmação o argumento messagenão é usado.
- O argumento windowé ignorado já que não é possível fazer essa confirmação um diálogo modal.
Bookmarks array
showOpenDialog and showSaveDialog resolve to an object with a bookmarks field. This field is an array of Base64 encoded strings that contain the security scoped bookmark data for the saved file. The securityScopedBookmarks option must be enabled for this to be present.
| Build Type | securityScopedBookmarks boolean | Return Type | Return Value | 
|---|
| macOS mas | True | Sucesso | ['LONGBOOKMARKSTRING'] | 
| macOS mas | True | Erro | [''](array of empty string) | 
| macOS mas | False | NA | [](empty array) | 
| non mas | any | NA | [](empty array) | 
Sheets
On macOS, dialogs are presented as sheets attached to a window if you provide a BaseWindow reference in the window parameter, or modals if no window is provided.
You can call BaseWindow.getCurrentWindow().setSheetOffset(offset) to change the offset from the window frame where sheets are attached.