对话框
显示用于打开和保存文件、警报等的本机系统对话框。
进程:主进程
这个对话框从Electron主线程打开。 如果你想要从一个渲染线程使用对话框对象,记得通过remote去访问它。
const { dialog } = require(‘electron’).remote
console.log(dialog)
文档地址:对话框
方法:
- dialog.showOpenDialogSync([browserWindow, ]options)
Returns String[] | undefined- dialog.showSaveDialogSync([browserWindow, ]options)
Returns String | undefined- dialog.showMessageBoxSync([browserWindow, ]options)
Returns Integer注意:不加Sync的方法为异步方法返回值为Returns Promise,可以在方法执行完毕后直接.then拿结果。
实例:
// index.html
<div>
<h2>openDialog</h2>
<button onclick="openDialog() ">打开</button>
<button onclick="saveDialog() ">保存</button>
<button onclick="popDialog() ">弹框</button>
</div>
// renderer.js
let path1;
function openDialog() {
path1 = dialog.showOpenDialogSync({
title: '请选择您喜欢的文件:',
buttonLabel: '揍你',
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] },
{ name: 'Custom File Type', extensions: ['js', 'html', 'json'] },
{ name: 'All Files', extensions: ['*'] }
]
})
// 下面即为异步方法:
// dialog.showOpenDialog({
// properties: ['openFile', 'openDirectory']
// }).then(result => {
// console.log(result.canceled)
// console.log(result.filePaths)
// }).catch(err => {
// console.log(err)
// })
}
let path2;
function saveDialog() {
path2 = dialog.showSaveDialogSync({
title: '请选择您要保存的文件:',
buttonLabel: 'save',
filters: [
// { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
// { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
{ name: 'Custom File Type', extensions: ['js', 'html', 'json'] },
{ name: 'All Files', extensions: ['*'] }
]
})
}
function popDialog() {
dialog.showMessageBoxSync({
type: 'error',
title: '错误',
message: path1[0],
detail: path2
})
console.log('--------', path1);
}
踩坑:
- webPreferences: {
preload: path.join(__dirname, ‘preload.js’),
nodeIntegration: true,
enableRemoteModule: true // 此两处必须有,不然 const { dialog } = require(‘electron’).remote 报错
} - 内容安全策略(CSP):index.html 加入:
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'" >
标签, 否则Chrome浏览在执行<button onclick="openDialog() ">打开</button>
onclick方法时会报错:it violates the following Content Security Policy directive: “script-src ‘unsafe inline’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution.
以上两坑来自:electron-quick-start
Electron 文档 v11.1.1 版本