开发学院

您的位置:首页>教程>正文

教程正文

Electron 教程:Webview(浏览器控件)

  webview(浏览器控件)用于在Electron程序中嵌入网页内容。这些内容包含在webview容器中。应用程序中的嵌入式页面控制着这些内容的显示方式。

  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.jpg

  webview标签也可以用于其他资源。webview元素有一个在官方文档中列出的事件列表。根据webview中发生的事情,您可以使用这些事件来改进功能。

  每当您使用嵌入脚本或来自互联网的其他资源时,建议使用网webview。这是推荐的,因为它具有很大的安全优势,不妨碍正常行为。