Electron BrowserView 的使用

官方文档:
https://www.electronjs.org/docs/api/browser-view

创建和控制视图

进程:主进程

BrowserView 被用来让 BrowserWindow 嵌入更多的 web 内容。 它就像一个子窗口,除了它的位置是相对于父窗口。 这意味着可以替代webview标签.

示例

// 在主进程中.
const { BrowserView, BrowserWindow } = require('electron')

const win = new BrowserWindow({  800, height: 600 })

const view = new BrowserView()
win.setBrowserView(view)
view.setBounds({ x: 0, y: 0,  300, height: 300 })
view.webContents.loadURL('https://electronjs.org')

例:嵌入百度

在主线程中

//为了管理应用程序的生命周期事件以及创建和控制浏览器窗口,您从 electron 包导入了 app 和 BrowserWindow 模块 。
const { app, BrowserWindow,BrowserView } = require('electron')

//在此之后,你定义了一个创建 新的浏览窗口的函数并将 nodeIntegration 设置为 true,将 index.html 文件加载到窗口中(第 12 行,稍后我们将讨论该文件)
function createWindow () {
    const win = new BrowserWindow({
         800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
        }
    })

    win.loadFile('index.html')

	//创建对象
    const view = new BrowserView()
    //设置到主窗口
    win.setBrowserView(view)
    //设置在主窗口的位置和view的大小
    view.setBounds({ x: 0, y: 0,  300, height: 300 })
    view.webContents.loadURL('http://www.baidu.com')
}

//你通过调用 createWindow方法,在 electron app 第一次被初始化时创建了一个新的窗口。
app.whenReady().then(createWindow)

//您添加了一个新的侦听器,当应用程序不再有任何打开窗口时试图退出。 由于操作系统的 窗口管理行为 ,此监听器在 macOS 上是禁止操作的
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

//您添加一个新的侦听器,只有当应用程序激活后没有可见窗口时,才能创建新的浏览器窗口。 例如,在首次启动应用程序后或重启运行中的应用程序
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

效果

image-20210204110524252

new BrowserView([可选]) 实验功能

  •   options
    

    Object (可选)

实例属性

使用 new BrowserView 创建的对象具有以下属性:

view.webContents 实验功能

视图的WebContents 对象

实例方法

使用 new BrowserView创建的对象具有以下实例方法:

view.setAutoResize(options) 实验功能

  •   选项
    

    对象

    • width Boolean (optional) - If true, the view's width will grow and shrink together with the window. 默认值为 false
    • height Boolean (optional) - If true, the view's height will grow and shrink together with the window. 默认值为 false
    • horizontal Boolean (optional) - If true, the view's x position and width will grow and shrink proportionally with the window. 默认值为 false
    • vertical Boolean (optional) - If true, the view's y position and height will grow and shrink proportionally with the window. 默认值为 false

view.setBounds(bounds) 实验功能

调整视图的大小,并将它移动到窗口边界

view.getBounds() 实验功能

返回 Rectangle

The bounds of this BrowserView instance as Object.

view.setBackgroundColor(color) 实验功能

  • color String - Color in #aarrggbb or #argb form. The alpha channel is optional.
原文地址:https://www.cnblogs.com/makalochen/p/14371495.html