我刚接触Electron,希望您能谅解我的知识有限。我想从主.js模板菜单中的'保存'选项中保存HTML文件。
应用程序加载正常,但当我进入菜单并点击保存或打开时,就会出现错误。1我已经尝试了很多种不同的方法,但仍无法消除上述错误。
以下是我的代码:
const {BrowserWindow, app, Menu, remote} = require('electron')
const fs = require('fs')
const url = require('url')
const path = require('path')
var dialog = require('electron').remote
app.on('ready', () => {
let mainWindow = new BrowserWindow({})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}));
mainWindow.webContents.on('will-navigate', (e, url) => {
e.preventDefault()
mainWindow.webContents.send('open-file', url.slice(7))
})
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);
});
//menu template
const mainMenuTemplate = [
{
label: 'File',
submenu: [
{label: 'New File',
accelerator: process.platform == 'darwin' ? 'Command+N' : 'Ctrl+N',
click(){
//create new file
}
},
{label: 'Open File',
accelerator: process.platform == 'darwin' ? 'Command+O' : 'Ctrl+O',
click(){
dialog.showOpenDialog();
}
},
{label: 'Save',
accelerator: process.platform == 'darwin' ? 'Command+S' : 'Ctrl+S',
click(){
dialog.showSaveDialog((fileName) => {
if(fileName === undefined) {
alert("File not saved");
return;
}
var content = docment.getElementById('#container').value;
fs.writeFile(fileName, content, (err) => {
if (err) console.log(err);
alert("Save Succesful!")
});
});
}
},
{label: 'Save As...',
accelerator: process.platform == 'darwin' ? 'Command+Sft+S' : 'Ctrl+Sft+S',
click(){
//create new file
}
},
{role: 'quit',
accelerator: process.platform == 'darwin' ? 'Command+F4' : 'Ctrl+F4' //Shortcuts
}
]
}
];
app.on('window-al
dialog
未定义。 - Terry Wei