目录解构
- main.js:主进程文件,用来控制整个应用程序(仅有一个)
- index.html:渲染模板
- render/index.js:渲染进程文件,用来控制页面的渲染(可有多个)
- package.json:依赖包
主进程代码
在electron中,主进程main.js有且仅有一个,用来控制整个引用程序。
// 主进程
// 引入electron模块
const electron = require('electron');
const path = require('path');
// 引用app
const app = electron.app;
// 引用浏览器窗口
const BrowserWindow = electron.BrowserWindow;
// 变量,保存对应用窗口的引用
let win = null;
const closeWindow = () => {
// 手动进行垃圾回收
win = null;
};
const createWindow = () => {
// 创建浏览器窗口实例,并赋值给win
win = new BrowserWindow({
// 软件默认打开的宽高
width: 800,
height: 600,
// 渲染进程集成node
webPreferences: {
nodeIntegration: true
},
});
// 加载index.html到窗口
win.loadFile('index.html');
// const url = path.resolve('file:', __dirname, 'index.html');
// console.log(url);
// win.loadURL(url);
// 调试模式打开控制台
win.webContents.openDevTools();
win.on('closed', closeWindow)
};
app.on('ready', createWindow);
package.json
"scripts": {
"start": "electron main.js"
},
渲染进程模板
在electron中的渲染进程模板即要渲染的页面。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.content {
width: 100%;
height: 400px;
background: orange;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="content"></div>
<script src="render/index.js"></script>
</body>
</html>
渲染进程
渲染进程即要渲染的模板他的js文件,在这里面可以用nodejs的模块操作。但是不建议,因为这样会引起安全问题,在控制台也会有警告。
// h5拖放API应用
let content = document.querySelector('.content');
const fs = require('fs');
// 引入iconv-lite包,解决windows下以GBK编码时中文乱码的问题
const iconv = require('iconv-lite');
content.ondragenter = content.ondragover = content.ondragleave = function (e) {
return false
};
content.ondrop = function (e) {
e.preventDefault();
// 得到拖过来的txt文件的地址
let path = e.dataTransfer.files[0].path;
// 通过fs模块读取对应的文件,然后渲染到content容器
fs.promises.readFile(path, {encoding: 'binary'})
.then(data => {
const buf = new Buffer(data, 'binary');
content.innerHTML = iconv.decode(buf, 'GBK');
})
.catch(err => {
console.log(err)
})
};