Electron BrowserView 的使用


官方文檔:
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()
    }
})

效果

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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM