目录

电子 - Webview( Webview)

webview标记用于在您的Electron应用中嵌入“来宾”内容,例如网页。 此内容包含在webview容器中。 应用内的嵌入式页面控制着如何显示此内容。

webview在与您的应用程序不同的进程中运行。 为确保恶意内容的安全性,webview与您的网页没有相同的权限。 这可以确保您的应用免受嵌入内容的侵害。 您的应用与嵌入页面之间的所有互动都将是异步的。

让我们考虑一个示例来了解在我们的Electron应用程序中嵌入外部网页。 我们将在我们的应用程序中嵌入iowiki网站的右侧。 使用以下内容创建一个新的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)

现在我们已经设置了主要流程,让我们创建将嵌入iowiki网站的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.iowiki.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元素包含在官方文档中列出的事件列表。 您可以使用这些事件来改进功能,具体取决于webview中发生的事情。

无论何时从Internet嵌入脚本或其他资源,建议使用webview。 建议使用它,因为它具有很高的安全性,并且不会妨碍正常行为。

↑回到顶部↑
WIKI教程 @2018