electron-vite_4使用WebContentsView快速集成已有项目

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值