首页 > 解决方案 > 从 Electron 中的 Webview 获取 BrowserView 的大小

问题描述

我正在尝试在位于其他元素下方的 Webview 中添加此处所见的功能。因此,它获得的 x 和 y 值当然只是 webview 本身,但该inspectElement()方法需要将窗口的 x 和 y 值作为一个整体来获取,而不仅仅是 webview。所以我需要能够获得整个窗口的高度,这样我就可以做一些数学运算来抵消我传入的值inspectElement()

当我打电话时这个答案remote.getCurrentWindow()我得到这个错误

Uncaught TypeError: Cannot read property 'getSize' of null
    at click (<anonymous>:3950:147)
    at CallbacksRegistry.apply (<anonymous>:1090:25)
    at handleMessage (<anonymous>:898:21)
    at EventEmitter.ipcRenderer.on.args (<anonymous>:888:7)
    at EventEmitter.emit (<anonymous>:5163:17)
    at Object.ipcNative.onInternalMessage (<anonymous>:3010:15)

所以它返回null。因此,这个答案是不够的。我似乎在 StackOverflow 或其他网站上找不到任何关于如何从 webview 获取窗口高度或 webview 从窗口本身偏移多少的信息。

标签: webviewelectron

解决方案


经过一番调查和阅读文档后,我得到了这个解决方案。

这是一个函数,您将 webContents 传递给此函数,然后您可以访问 BrowserWindow

function getBrowserWindowFromWebContents(
  contents: Electron.WebContents
): Electron.BrowserWindow {
  let topContents = contents
  while (topContents.hostWebContents) {
    topContents = topContents.hostWebContents
  }

  return remote.BrowserWindow.fromWebContents(topContents)
}

然后我们可以访问getSize()

getBrowserWindowFromWebContents(remote.getCurrentWebContents()).getSize()

我们走了:)


推荐阅读