BrowserWindow
# 认识BrowserWindow
在Electron中,我们借助它内置的BrowserWindow
方法来实现窗口的开启
const { app, BrowserWindow } = require('electron')
app.on('ready', () => {
let mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
mainWindow.loadFile('index.html')
let secondWindow = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
nodeIntegration: true
},
parent: mainWindow
})
secondWindow.loadFile('second.html')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
在main.js
中,app
监听ready
状态,开启一个新的窗口,加载index.html
文件,这里还开启了第二个窗口,它是主窗口的子窗口,根据parent
属性指定,nodeIntegration
属性指定在js文件中可以使用node
环境提供的API,不过在最新的20版本中,还需要把contextIsolation
选项置为false
才可以使用。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<link href="./styles.css" rel="stylesheet">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
index.html
中引用了renderer.js
文件
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('node-version').innerHTML = process.versions.node
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
在renderer.js
中,我们使用了DOM
和Node
提供的API,将本机的Node
版本输出到窗口中
编辑 (opens new window)
上次更新: 2022/09/08, 15:49:40