範例總覽
在本節中,我們收集了一組指南,介紹您可能想要在 Electron 應用程式中實作的常見功能。每個指南都包含一個最小、獨立的範例應用程式中的實用範例。執行這些範例最簡單的方法是下載 Electron Fiddle。
安裝 Fiddle 後,您可以按下您將在以下程式碼範例中找到的「在 Fiddle 中開啟」按鈕
- main.js
- preload.js
- index.html
const { app, BrowserWindow } = require('electron/main')
const path = require('node:path')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
</body>
</html>
如何...?
您可以在側邊欄中找到完整的「如何...?」清單。如果有些您想做的事情沒有記錄下來,請加入我們的 Discord 伺服器 並告訴我們!