Skip to main content

dialog

Display native system dialogs for opening and saving files, alerting, etc.显示用于打开和保存文件、报警等的本地系统对话框。

Process: 流程Main

An example of showing a dialog to select multiple files:显示用于选择多个文件的对话框的示例:

const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

Methods方法

The dialog module has the following methods:dialog模块具有以下方法:

dialog.showOpenDialogSync([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • title string (optional)
    • defaultPath string (optional)
    • buttonLabel string (optional) - Custom label for the confirmation button, when left empty the default label will be used.确认按钮的自定义标签,当保留为空时,将使用默认标签。
    • filters FileFilter[] (optional)
    • properties string[] (optional) - Contains which features the dialog should use. 包含对话框应使用的功能。The following values are supported:支持以下值:
      • openFile - Allow files to be selected.允许选择文件。
      • openDirectory - Allow directories to be selected.允许选择目录。
      • multiSelections - Allow multiple paths to be selected.允许选择多个路径。
      • showHiddenFiles - Show hidden files in dialog.在对话框中显示隐藏的文件。
      • createDirectory macOS - Allow creating new directories from dialog.允许从对话框创建新目录。
      • promptToCreate Windows - Prompt for creation if the file path entered in the dialog does not exist. 如果在对话框中输入的文件路径不存在,则提示创建。This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application.这实际上不会在路径上创建文件,但允许返回应用程序应该创建的不存在的路径。
      • noResolveAliases macOS - Disable the automatic alias (symlink) path resolution. 禁用自动别名(符号链接)路径解析。Selected aliases will now return the alias path instead of their target path.所选别名现在将返回别名路径,而不是其目标路径。
      • treatPackageAsDirectory macOS - Treat packages, such as .app folders, as a directory instead of a file.将包(如.app文件夹)视为目录而非文件。
      • dontAddToRecent Windows - Do not add the item being opened to the recent documents list.不要将正在打开的项目添加到最近的文档列表中。
    • message string (optional) macOS - Message to display above input boxes.要在输入框上方显示的消息。
    • securityScopedBookmarks boolean (optional) macOS mas - Create security scoped bookmarks when packaged for the Mac App Store.为Mac应用商店打包时创建安全范围的书签

Returns string[] | undefined, the file paths chosen by the user; if the dialog is cancelled it returns undefined.返回string[] | undefined,即用户选择的文件路径;如果对话框被取消,则返回undefined

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。

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. filters指定了一组文件类型,当您希望将用户限制为特定类型时,可以显示或选择这些类型。For example:例如:

{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['as'] },
{ name: 'All Files', extensions: ['*'] }
]
}

The extensions array should contain extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). 扩展名数组应包含不带通配符或句点的扩展名(例如,'png'很好,但'.png''*.png'不好)。To show all files, use the '*' wildcard (no other wildcard is supported).要显示所有文件,请使用'*'通配符(不支持其他通配符)。

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.在Windows和Linux上,打开的对话框不能既是文件选择器又是目录选择器,因此,如果在这些平台上将properties设置为['openFile', 'openDirectory'],则会显示目录选择器。

dialog.showOpenDialogSync(mainWindow, {
properties: ['openFile', 'openDirectory']
})

dialog.showOpenDialog([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • title string (optional)
    • defaultPath string (optional)
    • buttonLabel string (optional) - Custom label for the confirmation button, when left empty the default label will be used.确认按钮的自定义标签,当保留为空时,将使用默认标签。
    • filters FileFilter[] (optional)
    • properties string[] (optional) - Contains which features the dialog should use. 包含对话框应使用的功能。The following values are supported:支持以下值:
      • openFile - Allow files to be selected.允许选择文件。
      • openDirectory - Allow directories to be selected.允许选择目录。
      • multiSelections - Allow multiple paths to be selected.允许选择多个路径。
      • showHiddenFiles - Show hidden files in dialog.在对话框中显示隐藏的文件。
      • createDirectory macOS - Allow creating new directories from dialog.允许从对话框创建新目录。
      • promptToCreate Windows - Prompt for creation if the file path entered in the dialog does not exist. 如果在对话框中输入的文件路径不存在,则提示创建。This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application.这实际上不会在路径上创建文件,但允许返回应用程序应该创建的不存在的路径。
      • noResolveAliases macOS - Disable the automatic alias (symlink) path resolution. 禁用自动别名(符号链接)路径解析。Selected aliases will now return the alias path instead of their target path.所选别名现在将返回别名路径,而不是其目标路径。
      • treatPackageAsDirectory macOS - Treat packages, such as .app folders, as a directory instead of a file.将包(如.app文件夹)视为目录而非文件。
      • dontAddToRecent Windows - Do not add the item being opened to the recent documents list.不要将正在打开的项目添加到最近的文档列表中。
    • message string (optional) macOS - Message to display above input boxes.要在输入框上方显示的消息。
    • securityScopedBookmarks boolean (optional) macOS mas - Create security scoped bookmarks创建安全范围的书签 when packaged for the Mac App Store.当为Mac应用商店打包时。

Returns 返回Promise<Object> - Resolve with an object containing the following:使用包含以下内容的对象进行解析:

  • canceled boolean - whether or not the dialog was canceled.无论对话框是否被取消。
  • filePaths string[] - An array of file paths chosen by the user. 由用户选择的一组文件路径。If the dialog is cancelled this will be an empty array.如果对话框被取消,这将是一个空数组。
  • bookmarks string[] (optional) macOS mas - An array matching the filePaths array of base64 encoded strings which contains security scoped bookmark data. filePaths数组匹配的数组,该数组由base64编码的字符串组成,包含安全范围的书签数据。securityScopedBookmarks must be enabled for this to be populated. 必须启用securityScopedBookmarks才能填充。(For return values, see table here.)(有关返回值,请参阅此处的表。)

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。

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. filters指定了一组文件类型,当您希望将用户限制为特定类型时,可以显示或选择这些类型。For example:例如:

{
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['as'] },
{ name: 'All Files', extensions: ['*'] }
]
}

The extensions array should contain extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). extensions数组应包含不带通配符或句点的扩展名(例如,'png'很好,但'.png''*.png'不好)。To show all files, use the '*' wildcard (no other wildcard is supported).要显示所有文件,请使用'*'通配符(不支持其他通配符)。

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.在Windows和Linux上,打开的对话框不能既是文件选择器又是目录选择器,因此,如果在这些平台上将properties设置为['openFile', 'openDirectory'],则会显示目录选择器。

dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'openDirectory']
}).then(result => {
console.log(result.canceled)
console.log(result.filePaths)
}).catch(err => {
console.log(err)
})

dialog.showSaveDialogSync([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • title string (optional) - The dialog title. 对话框标题。Cannot be displayed on some Linux desktop environments.无法在某些Linux桌面环境中显示。
    • defaultPath string (optional) - Absolute directory path, absolute file path, or file name to use by default.默认情况下使用的绝对目录路径、绝对文件路径或文件名。
    • buttonLabel string (optional) - Custom label for the confirmation button, when left empty the default label will be used.确认按钮的自定义标签,当保留为空时,将使用默认标签。
    • filters FileFilter[] (optional)
    • message string (optional) macOS - Message to display above text fields.要显示在文本字段上方的消息。
    • nameFieldLabel string (optional) macOS - Custom label for the text displayed in front of the filename text field.显示在文件名文本字段前面的文本的自定义标签。
    • showsTagField boolean (optional) macOS - Show the tags input box, defaults to true.显示标记输入框,默认为true
    • properties string[] (optional)
      • showHiddenFiles - Show hidden files in dialog.在对话框中显示隐藏的文件。
      • createDirectory macOS - Allow creating new directories from dialog.允许从对话框创建新目录。
      • treatPackageAsDirectory macOS - Treat packages, such as .app folders, as a directory instead of a file.将包(如.app文件夹)视为目录而非文件。
      • showOverwriteConfirmation Linux - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.设置如果用户键入已存在的文件名,是否向用户显示确认对话框。
      • dontAddToRecent Windows - Do not add the item being saved to the recent documents list.不要将正在保存的项目添加到最近的文档列表中。
    • securityScopedBookmarks boolean (optional) macOS mas - Create a security scoped bookmark when packaged for the Mac App Store. 为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 | undefined, the path of the file chosen by the user; if the dialog is cancelled it returns undefined.,用户选择的文件的路径;如果对话框被取消,则返回undefined

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。

The filters specifies an array of file types that can be displayed, see dialog.showOpenDialog for an example.filters指定可以显示的文件类型数组,请参阅dialog.showOpenDialog以获取示例。

dialog.showSaveDialog([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • title string (optional) - The dialog title. 对话框标题。Cannot be displayed on some Linux desktop environments.无法在某些Linux桌面环境中显示。
    • defaultPath string (optional) - Absolute directory path, absolute file path, or file name to use by default.默认情况下使用的绝对目录路径、绝对文件路径或文件名。
    • buttonLabel string (optional) - Custom label for the confirmation button, when left empty the default label will be used.确认按钮的自定义标签,当保留为空时,将使用默认标签。
    • filters FileFilter[] (optional)
    • message string (optional) macOS - Message to display above text fields.要显示在文本字段上方的消息。
    • nameFieldLabel string (optional) macOS - Custom label for the text displayed in front of the filename text field.显示在文件名文本字段前面的文本的自定义标签。
    • showsTagField boolean (optional) macOS - Show the tags input box, defaults to true.显示标记输入框,默认为true
    • properties string[] (optional)
      • showHiddenFiles - Show hidden files in dialog.在对话框中显示隐藏的文件。
      • createDirectory macOS - Allow creating new directories from dialog.允许从对话框创建新目录。
      • treatPackageAsDirectory macOS - Treat packages, such as .app folders, as a directory instead of a file.将包(如.app文件夹)视为目录而非文件。
      • showOverwriteConfirmation Linux - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.设置如果用户键入已存在的文件名,是否向用户显示确认对话框。
      • dontAddToRecent Windows - Do not add the item being saved to the recent documents list.不要将正在保存的项目添加到最近的文档列表中。
    • securityScopedBookmarks boolean (optional) macOS mas - Create a security scoped bookmark when packaged for the Mac App Store. 为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:使用包含以下内容的对象进行解析:

  • canceled boolean - whether or not the dialog was canceled.无论对话框是否被取消。
  • filePath string (optional) - If the dialog is canceled, this will be undefined.如果对话框被取消,这将是undefined
  • bookmark string (optional) macOS mas - Base64 encoded string which contains the security scoped bookmark data for the saved file. Base64编码的字符串,其中包含已保存文件的安全范围书签数据。securityScopedBookmarks must be enabled for this to be present. 必须启用securityScopedBookmarks才能使其存在。(For return values, see table here.)(有关返回值,请参阅此处的表。)

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。

The filters specifies an array of file types that can be displayed, see dialog.showOpenDialog for an example.filters指定可以显示的文件类型数组,请参阅dialog.showOpenDialog以获取示例。

Note: On macOS, using the asynchronous version is recommended to avoid issues when expanding and collapsing the dialog.在macOS上,建议使用异步版本,以避免在展开和折叠对话框时出现问题。

dialog.showMessageBoxSync([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • message string - Content of the message box.消息框的内容。
    • type string (optional) - Can be "none", "info", "error", "question" or "warning". 可以是"none""info""error""question""warning"On Windows, "question" displays the same icon as "info", unless you set an icon using the "icon" option. 在Windows上,"question"显示的图标与"info"相同,除非您使用"icon"选项设置图标。On macOS, both "warning" and "error" display the same warning icon.在macOS上,"warning""error"都显示相同的警告图标。
    • buttons string[] (optional) - Array of texts for buttons. On Windows, an empty array will result in one button labeled "OK".按钮的文本数组。在Windows上,一个空数组将产生一个标记为“确定”的按钮。
    • defaultId Integer (optional) - Index of the button in the buttons array which will be selected by default when the message box opens.按钮阵列中按钮的索引,当消息框打开时,默认情况下会选择该按钮。
    • title string (optional) - Title of the message box, some platforms will not show it.消息框的标题,某些平台不会显示。
    • detail string (optional) - Extra information of the message.消息的额外信息。
    • icon (NativeImage | string) (optional)
    • textWidth Integer (optional) macOS - Custom width of the text in the message box.消息框中文本的自定义宽度。
    • cancelId Integer (optional) - The index of the button to be used to cancel the dialog, via the Esc key. 用于通过Esc键取消对话框的按钮的索引。By default this is assigned to the first button with "cancel" or "no" as the label. 默认情况下,这会分配给第一个以“取消”或“否”为标签的按钮。If no such labeled buttons exist and this option is not set, 0 will be used as the return value.如果不存在此类标记按钮,并且未设置此选项,则将使用0作为返回值。
    • noLink boolean (optional) - On Windows Electron will try to figure out which one of the buttons are common buttons (like "Cancel" or "Yes"), and show the others as command links in the dialog. 在Windows上,Electron将尝试找出其buttons中的哪一个是常见按钮(如“取消”或“是”),并在对话框中显示其他按钮作为命令链接。This can make the dialog appear in the style of modern Windows apps. 这可以使对话框以现代Windows应用程序的样式显示。If you don't like this behavior, you can set noLink to true.如果您不喜欢这种行为,可以将noLink设置为true
    • normalizeAccessKeys boolean (optional) - Normalize the keyboard access keys across platforms. 跨平台规范化键盘访问键。Default is false. 默认值为falseEnabling this assumes & is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, & characters are removed on macOS, converted to _ on Linux, and left untouched on Windows. 启用此选项假设&用于放置键盘快捷键的按钮标签,标签将被转换,以便在每个平台上正确工作,&字符在macOS上被删除,在Linux上被转换为_,在Windows上保持不变。For example, a button label of Vie&w will be converted to Vie_w on Linux and View on macOS and can be selected via Alt-W on Windows and Linux.例如,Vie&w的按钮标签将在Linux上转换为Vie_w,在macOS上转换为View,并且可以在Windows和Linux上通过Alt-w进行选择。

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.显示一个消息框,它将阻止进程,直到消息框关闭。它返回被单击按钮的索引。

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal. browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。If browserWindow is not shown dialog will not be attached to it. 如果browserWindow没有显示,对话框将不会附加到它。In such case it will be displayed as an independent window.在这种情况下,它将显示为一个独立的窗口。

dialog.showMessageBox([browserWindow, ]options)

  • browserWindow BrowserWindow (optional)
  • options Object
    • message string - Content of the message box.消息框的内容。
    • type string (optional) - Can be "none", "info", "error", "question" or "warning". 可以是"none""info""error""question""warning"On Windows, "question" displays the same icon as "info", unless you set an icon using the "icon" option. 在Windows上,"question"显示的图标与"info"相同,除非您使用"icon"选项设置图标。On macOS, both "warning" and "error" display the same warning icon.在macOS上,"warning""error"都显示相同的警告图标。
    • buttons string[] (optional) - Array of texts for buttons. 按钮的文本数组。On Windows, an empty array will result in one button labeled "OK".在Windows上,一个空数组将产生一个标记为“确定”的按钮。
    • defaultId Integer (optional) - Index of the button in the buttons array which will be selected by default when the message box opens.按钮阵列中按钮的索引,当消息框打开时,默认情况下会选择该按钮。
    • signal AbortSignal (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. 传递AbortSignal的实例以选择性地关闭消息框,消息框将表现为被用户取消。On macOS, signal does not work with message boxes that do not have a parent window, since those message boxes run synchronously due to platform limitations.在macOS上,signal不适用于没有父窗口的消息框,因为这些消息框由于平台限制而同步运行。
    • title string (optional) - Title of the message box, some platforms will not show it.消息框的标题,某些平台不会显示。
    • detail string (optional) - Extra information of the message.消息的额外信息。
    • checkboxLabel string (optional) - If provided, the message box will include a checkbox with the given label.如果提供,消息框将包括一个带有给定标签的复选框。
    • checkboxChecked boolean (optional) - Initial checked state of the checkbox. 复选框的初始选中状态。false by default.默认情况下为false
    • icon (NativeImage | string) (optional)
    • textWidth Integer (optional) macOS - Custom width of the text in the message box.消息框中文本的自定义宽度。
    • cancelId Integer (optional) - The index of the button to be used to cancel the dialog, via the Esc key. 用于通过Esc键取消对话框的按钮的索引。By default this is assigned to the first button with "cancel" or "no" as the label. 默认情况下,这会分配给第一个以“取消”或“否”为标签的按钮。If no such labeled buttons exist and this option is not set, 0 will be used as the return value.如果不存在此类标记按钮,并且未设置此选项,则将使用0作为返回值。
    • noLink boolean (optional) - On Windows Electron will try to figure out which one of the buttons are common buttons (like "Cancel" or "Yes"), and show the others as command links in the dialog. 在Windows上,Electron将尝试找出其buttons中的哪一个是常见按钮(如“取消”或“是”),并在对话框中显示其他按钮作为命令链接。This can make the dialog appear in the style of modern Windows apps. 这可以使对话框以现代Windows应用程序的样式显示。If you don't like this behavior, you can set noLink to true.如果您不喜欢这种行为,可以将noLink设置为true
    • normalizeAccessKeys boolean (optional) - Normalize the keyboard access keys across platforms. 跨平台规范化键盘访问键。Default is false. 默认值为falseEnabling this assumes & is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, & characters are removed on macOS, converted to _ on Linux, and left untouched on Windows. 启用此选项假设&用于放置键盘快捷键的按钮标签,标签将被转换,以便在每个平台上正确工作,字符&在macOS上被删除,在Linux上被转换为_,在Windows上保持不变。For example, a button label of Vie&w will be converted to Vie_w on Linux and View on macOS and can be selected via Alt-W on Windows and Linux.例如,Vie&w的按钮标签将在Linux上转换为Vie_w,在macOS上转换为View,并且可以在Windows和Linux上通过Alt-w进行选择。

Returns 返回Promise<Object> - resolves with a promise containing the following properties:通过包含以下属性的承诺解决:

  • response number - The index of the clicked button.单击按钮的索引。
  • checkboxChecked boolean - The checked state of the checkbox if checkboxLabel was set. 如果设置了checkboxLabel,则复选框的选中状态。Otherwise false.否则为false

Shows a message box.显示一个消息框。

The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.browserWindow参数允许对话框将自己附加到父窗口,使其成为模态窗口。

dialog.showErrorBox(title, content)

  • title string - The title to display in the error box.要在错误框中显示的标题。
  • content string - The text content to display in the error box.要在错误框中显示的文本内容。

Displays a modal dialog that shows an error message.显示一个显示错误消息的模式对话框。

This API can be called safely before the ready event the app module emits, it is usually used to report errors in early stage of startup. 此API可以在应用程序模块发出ready事件之前安全调用,通常用于在启动的早期报告错误。If called before the app readyevent on Linux, the message will be emitted to stderr, and no GUI dialog will appear.如果在Linux上的应用程序ready事件之前调用,则消息将发送到stderr,并且不会出现GUI对话框。

dialog.showCertificateTrustDialog([browserWindow, ]options) macOS Windows

  • browserWindow BrowserWindow (optional)
  • options Object
    • certificate Certificate - The certificate to trust/import.要信任/导入的证书。
    • message string - The message to display to the user.要显示给用户的消息。

Returns 返回Promise<void> - resolves when the certificate trust dialog is shown.在显示证书信任对话框时解析。

On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. 在macOS上,这会显示一个模式对话框,其中显示消息和证书信息,并为用户提供信任/导入证书的选项。If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.如果提供browserWindow参数,则对话框将附加到父窗口,使其成为模态对话框。

On Windows the options are more limited, due to the Win32 APIs used:在Windows上,由于使用了Win32 API,选项受到更多限制:

  • The message argument is not used, as the OS provides its own confirmation dialog.不使用message参数,因为操作系统提供了自己的确认对话框。
  • The browserWindow argument is ignored since it is not possible to make this confirmation dialog modal.browserWindow参数被忽略,因为无法将此确认对话框设置为模式。

Bookmarks array书签数组

showOpenDialog, showOpenDialogSync, showSaveDialog, and showSaveDialogSync will return a bookmarks array.showOpenDialogshowOpenDialogSyncshowSaveDialogshowSaveDialogSync将返回bookmarks数组

Build Type生成类型securityScopedBookmarks booleanReturn Type返回类型Return Value返回值
macOS masTrueSuccess['LONGBOOKMARKSTRING']
macOS masTrueError[''] (array of empty string)
macOS masFalseNA[] (empty array)
non masanyNA[] (empty array)

Sheets

On macOS, dialogs are presented as sheets attached to a window if you provide a BrowserWindow reference in the browserWindow parameter, or modals if no window is provided.在macOS上,如果在browserWindow参数中提供BrowserWindow引用,则对话框显示为附加到窗口的工作表,如果没有提供窗口,则显示为模态。

You can call BrowserWindow.getCurrentWindow().setSheetOffset(offset) to change the offset from the window frame where sheets are attached.您可以调用BrowserWindow.getCurrentWindow().setSheetOffset(offset)来更改附着图纸的窗口框架的偏移量。