Web 嵌入官方推荐使用WebContentsView;集成也比较简单,但还是需要你单独写点东西;
src/main/index.ts进行修改
import { app,
shell, BrowserWindow,
ipcMain, nativeImage, WebContentsView, dialog } from 'electron';
function createWindow(): void {
// 1.创建 browser window.
const mainWindow = new BrowserWindow({
width: 900,
height: 670,
show: false,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon: appIcon } : {}),
transparent: false,
frame: true,
resizable: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
// 2.创建WebContentsView
const view1 = new WebContentsView()
// 3. 添加给mainWindow
mainWindow.contentView.addChildView(view1)
// 4.知道要加载的线上url最好是https
view1.webContents.loadURL('https://baidu.com')
// 5.指定显示位置;x,y是偏移;这里选择0;width和height和mainWindow保持一致
view1.setBounds({ x: 0, y: 0, width: 900, height: 670});
// 染进程第一次完成绘制时
mainWindow.on('ready-to-show', () => {
// 6-1.关闭谷歌调试工具
mainWindow.webContents.closeDevTools();
// 6-2.当页面发生改变的时候重新指定显示位置
mainWindow.on('resize', () => {
// 获取mainWindow宽高
const [width, height] = mainWindow.getContentSize();
view1.setBounds({ x: 0, y: 0, width, height});
});
mainWindow.show()
})
mainWindow.webContents.setWindowOpenHandler((details) => {
shell.openExternal(details.url)
return { action: 'deny' }
})
// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
} else {
// 7.注意这里一定要加载index.html
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
}
}
renderer/index.html
注意修改title, 比方说‘微信’、‘钉钉’、‘小红书’、‘有道云’
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>百度</title>
</head>
<body>
</body>
</html>