示例预览

在本节中,我们收集了一些新手通用的功能示例,可以让你快速实现需要的 Electron 应用。 每个例子都包含一个简单的、自成一体的示例应用程序。 运行这些示例的最简单方法是下载 Electron Fiddle

一旦安装了Fiddle,就可以按下 “Open in Fiddle”按钮,然后会在下面找到以下代码样本:

  • index.html
  • main.js
  • preload.js
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Hello World!</title>
  6. <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  7. </head>
  8. <body>
  9. <h1>Hello World!</h1>
  10. <p>
  11. We are using Node.js <span id="node-version"></span>,
  12. Chromium <span id="chrome-version"></span>,
  13. and Electron <span id="electron-version"></span>.
  14. </p>
  15. </body>
  16. </html>
  1. const { app, BrowserWindow } = require('electron')
  2. const path = require('path')
  3. function createWindow () {
  4. const win = new BrowserWindow({
  5. width: 800,
  6. height: 600,
  7. webPreferences: {
  8. preload: path.join(__dirname, 'preload.js')
  9. }
  10. })
  11. win.loadFile('index.html')
  12. }
  13. app.whenReady().then(() => {
  14. createWindow()
  15. app.on('activate', () => {
  16. if (BrowserWindow.getAllWindows().length === 0) {
  17. createWindow()
  18. }
  19. })
  20. })
  21. app.on('window-all-closed', () => {
  22. if (process.platform !== 'darwin') {
  23. app.quit()
  24. }
  25. })
  1. window.addEventListener('DOMContentLoaded', () => {
  2. const replaceText = (selector, text) => {
  3. const element = document.getElementById(selector)
  4. if (element) element.innerText = text
  5. }
  6. for (const type of ['chrome', 'node', 'electron']) {
  7. replaceText(`${type}-version`, process.versions[type])
  8. }
  9. })

Open in Fiddle

How to…?

You can find the full list of “How to?” in the sidebar. If there is something that you would like to do that is not documented, please join our Discord server and let us know!