官方文檔:
https://www.electronjs.org/docs/api/browser-view
創建和控制視圖
進程:主進程
BrowserView 被用來讓 BrowserWindow 嵌入更多的 web 內容。 它就像一個子窗口,除了它的位置是相對於父窗口。 這意味着可以替代webview標簽.
示例
// 在主進程中.
const { BrowserView, BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
const view = new BrowserView()
win.setBrowserView(view)
view.setBounds({ x: 0, y: 0, width: 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({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
}
})
win.loadFile('index.html')
//創建對象
const view = new BrowserView()
//設置到主窗口
win.setBrowserView(view)
//設置在主窗口的位置和view的大小
view.setBounds({ x: 0, y: 0, width: 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()
}
})
效果

new BrowserView([可選\]) 實驗功能
-
optionsObject (可選)
webPreferencesObject (可選) - 詳情請看 BrowserWindow.
實例屬性
使用 new BrowserView 創建的對象具有以下屬性:
view.webContents 實驗功能
視圖的WebContents 對象
實例方法
使用 new BrowserView創建的對象具有以下實例方法:
view.setAutoResize(options) 實驗功能
-
選項對象
widthBoolean (optional) - Iftrue, the view's width will grow and shrink together with the window. 默認值為falseheightBoolean (optional) - Iftrue, the view's height will grow and shrink together with the window. 默認值為falsehorizontalBoolean (optional) - Iftrue, the view's x position and width will grow and shrink proportionally with the window. 默認值為falseverticalBoolean (optional) - Iftrue, the view's y position and height will grow and shrink proportionally with the window. 默認值為false
view.setBounds(bounds) 實驗功能
boundsRectangle
調整視圖的大小,並將它移動到窗口邊界
view.getBounds() 實驗功能
返回 Rectangle
The bounds of this BrowserView instance as Object.
view.setBackgroundColor(color) 實驗功能
colorString - Color in#aarrggbbor#argbform. The alpha channel is optional.
