5.4 加載和顯示不同類型的資源
Electron 支持加載和顯示多種類型的資源,包括圖片、視頻和其他靜態文件。
5.4.1 加載圖片的示例代碼
index.html:
<!DOCTYPE html>
<html>
<head><title>Load Image</title>
</head>
<body><h1>Load Image Example</h1><img src="path/to/image.jpg" alt="Example Image">
</body>
</html>
5.4.2 加載視頻的示例代碼
index.html:
<!DOCTYPE html>
<html>
<head><title>Load Video</title>
</head>
<body><h1>Load Video Example</h1><video width="600" controls><source src="path/to/video.mp4" type="video/mp4">Your browser does not support the video tag.</video>
</body>
</html>
5.5 處理加載錯誤
在加載內容時,可能會遇到各種錯誤,例如網絡問題或文件不存在。我們可以通過監聽 webContents
事件來處理這些錯誤。
5.5.1 處理加載錯誤的示例代碼
主進程代碼:
const { app, BrowserWindow } = require('electron');
const path = require('path');let mainWindow;const createMainWindow = () => {mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, 'preload.js'),contextIsolation: true,nodeIntegration: false}});// 監聽加載失敗事件mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {console.error(`Failed to load ${validatedURL}: ${errorDescription} (${errorCode})`);// 顯示錯誤頁面mainWindow.loadFile('error.html');});// 加載本地的 index.html 文件mainWindow.loadFile('index.html');// 打開開發者工具(僅在開發階段使用)mainWindow.webContents.openDevTools();mainWindow.on('closed', () => {mainWindow = null;});
};app.on('ready', createMainWindow);app.on('window-all-closed', () => {if (process.platform !== 'darwin') {app.quit();}
});app.on('activate', () => {if (mainWindow === null) {createMainWindow();}
});
error.html:
<!DOCTYPE html>
<html>
<head><title>Error</title>
</head>
<body><h1>Failed to load content</h1><p>There was an error loading the requested content. Please try again later.</p>
</body>
</html>
5.6 使用 WebView 標簽
WebView
標簽允許在 Electron 應用中嵌入其他 Web 內容,類似于一個嵌入的瀏覽器。它運行在獨立的進程中,并且具有更高的安全性和穩定性。
5.6.1 使用 WebView 標簽的示例代碼
index.html:
<!DOCTYPE html>
<html>
<head><title>WebView Example</title>
</head>
<body><h1>WebView Example</h1><webview id="foo" src="https://www.example.com" style="width:800px; height:600px"></webview>
</body>
</html>
主進程代碼:
const { app, BrowserWindow } = require('electron');
const path = require('path');let mainWindow;const createMainWindow = () => {mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, 'preload.js'),contextIsolation: true,nodeIntegration: false,webviewTag: true // 啟用 WebView 標簽}});mainWindow.loadFile('index.html');mainWindow.on('closed', () => {mainWindow = null;});
};app.on('ready', createMainWindow);app.on('window-all-closed', () => {if (process.platform !== 'darwin') {app.quit();}
});app.on('activate', () => {if (mainWindow === null) {createMainWindow();}
});
通過本章內容,你已經了解了如何在 Electron 應用中加載和顯示各種內容,包括本地 HTML 文件、遠程 URL、動態內容以及各種類型的資源,并處理加載錯誤和使用 WebView
標簽。接下來的章節將繼續深入探討更多高級功能和最佳實踐,幫助你進一步掌握 Electron 開發。