electron-quickstart

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
后一修订版
前一修订版
electron-quickstart [2026/11/03 23:47] – 追加目录结构与 package.json 张叶安electron-quickstart [2026/11/03 23:50] (当前版本) – 追加简化的 index.html 示例 张叶安
行 47: 行 47:
   }   }
 } }
 +</code>
 +
 +==== main.js ====
 +
 +主进程:创建窗口、注册 IPC 处理函数、管理应用生命周期。安全相关的三个选项保持安全取值。
 +
 +<code js>
 +const { app, BrowserWindow, ipcMain } = require('electron')
 +const path = require('node:path')
 +
 +function createWindow () {
 +  const win = new BrowserWindow({
 +    width: 1000,
 +    height: 700,
 +    show: false,
 +    webPreferences: {
 +      preload: path.join(__dirname, 'preload.js'),
 +      contextIsolation: true,
 +      nodeIntegration: false,
 +      sandbox: true
 +    }
 +  })
 +
 +  win.once('ready-to-show', () => win.show())   // 避免白屏闪烁
 +  win.loadFile('index.html')
 +}
 +
 +// 最典型的 IPC:渲染进程请求,主进程应答
 +ipcMain.handle('ping', () => 'pong from main')
 +
 +app.whenReady().then(() => {
 +  createWindow()
 +  app.on('activate', () => {
 +    if (BrowserWindow.getAllWindows().length === 0) createWindow()
 +  })
 +})
 +
 +app.on('window-all-closed', () => {
 +  if (process.platform !== 'darwin') app.quit()
 +})
 +</code>
 +
 +==== preload.js ====
 +
 +只通过 ''contextBridge'' 暴露最小粒度的 API,绝不整体暴露 ''ipcRenderer''。
 +
 +<code js>
 +const { contextBridge, ipcRenderer } = require('electron')
 +
 +contextBridge.exposeInMainWorld('api', {
 +  ping: () => ipcRenderer.invoke('ping'),
 +  electronVersion: process.versions.electron
 +})
 +</code>
 +
 +==== renderer.js ====
 +
 +这是普通网页脚本,拿不到 ''fs'' 等 Node 模块,需要系统能力时一律走 IPC。
 +
 +<code js>
 +document.getElementById('btn').addEventListener('click', async () => {
 +  const pong = await window.api.ping()
 +  document.getElementById('out').textContent =
 +    `${pong} / Electron ${window.api.electronVersion}`
 +})
 +</code>
 +
 +==== index.html ====
 +
 +用普通脚本标签引入同目录的 renderer.js,并声明一条基础 CSP,禁止内联脚本。
 +
 +<code html>
 +<!doctype html>
 +<h1>Hello Electron</h1>
 +<button id="btn">Ping 主进程</button>
 +<pre id="out"></pre>
 </code> </code>
  

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • electron-quickstart.1793720856.txt.gz
  • 最后更改: 2026/11/03 23:47
  • 由 张叶安