电子-Webview
webview 标签用于在 Electron 应用程序中嵌入“访客”内容,例如网页。此内容包含在 webview 容器中。应用程序中的嵌入页面控制此内容的显示方式。
webview 在与您的应用程序不同的进程中运行。为了确保免受恶意内容的安全,网络视图没有与您的网页相同的权限。这可以确保您的应用程序免受嵌入内容的影响。您的应用程序和嵌入页面之间的所有交互都将是异步的。
让我们考虑一个例子来了解外部网页在我们的 Electron 应用程序中的嵌入。我们将把tutorialspoint 网站嵌入到我们应用程序的右侧。使用以下内容创建一个新的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)
现在我们已经设置了主流程,让我们创建将嵌入tutorialspoint 网站的 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.tutorialspoint.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>
使用以下命令运行应用程序 -
$ electron ./main.js
上面的命令将生成以下输出 -
webview 标签也可用于其他资源。webview 元素具有官方文档中列出的它发出的事件列表。您可以使用这些事件来根据 web 视图中发生的事情来改进功能。
每当您嵌入来自 Internet 的脚本或其他资源时,建议使用 webview。推荐这样做,因为它具有很大的安全优势并且不会妨碍正常Behave。