Electron 网络视图
webview 标签用于在您的 Electron 应用程序中嵌入"访客"内容,例如网页。此内容包含在 webview 容器中。您应用中的嵌入页面控制着这些内容的显示方式。
网络视图在与您的应用程序不同的进程中运行。为确保免受恶意内容的侵害,webview 与您的网页具有不同的权限。这可以保护您的应用免受嵌入内容的影响。您的应用和嵌入页面之间的所有交互都将是异步的。
让我们考虑一个示例,以了解在我们的 Electron 应用中嵌入外部网页。我们将在我们的应用程序的右侧嵌入 lidihuo 网站。使用以下内容创建一个新的
main.js 文件-
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
现在我们已经设置了我们的主要流程,让我们创建将嵌入 lidihuo 网站的 HTML 文件。创建一个名为 index.html 的文件,内容如下-
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Menus</title>
</head>
<body>
<div>
<div>
<h2>We have the website embedded below!</h2>
</div>
<webview id = "foo" src = "https://www.lidihuo.com/" style =
"width:400px; height:480px;">
<div class = "indicator"></div>
</webview>
</div>
<script type = "text/javascript">
// Event handlers for loading events.
// Use these to handle loading screens, transitions, etc
onload = () => {
const webview = document.getElementById('foo')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
</body>
</html>
使用以下命令运行应用程序-
上述命令将生成以下输出-
webview 标签也可用于其他资源。 webview 元素有一个事件列表,它在官方文档中列出了它发出的事件。您可以使用这些事件来改进功能,具体取决于 Web 视图中发生的事情。
每当您从 Internet 嵌入脚本或其他资源时,建议使用 webview。建议这样做,因为它具有极大的安全优势,并且不会妨碍正常行为。