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://tutorialspoint.tw/" 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 元素會發出一些事件,這些事件在官方文件中有列出。你可以使用這些事件來改進功能,具體取決於 webview 中發生的事情。

無論何時嵌入來自網際網路的指令碼或其他資源,都建議使用 webview。這是推薦的做法,因為它具有極大的安全優勢,並且不會妨礙正常的行為。

廣告