Electron - 对话框

对话框

显示用于打开和保存文件、警报等的本机系统对话框。
进程:主进程
这个对话框从Electron主线程打开。 如果你想要从一个渲染线程使用对话框对象,记得通过remote去访问它。
const { dialog } = require(‘electron’).remote
console.log(dialog)

文档地址:对话框

方法

  1. dialog.showOpenDialogSync([browserWindow, ]options)
    Returns String[] | undefined
  2. dialog.showSaveDialogSync([browserWindow, ]options)
    Returns String | undefined
  3. 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);
}

踩坑:

  1. webPreferences: {
    preload: path.join(__dirname, ‘preload.js’),
    nodeIntegration: true,
    enableRemoteModule: true // 此两处必须有,不然 const { dialog } = require(‘electron’).remote 报错
    }
  2. 内容安全策略(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 版本
electron-quick-start

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值