Electron 提供了一個實時構建桌面應用的純 JavaScript 環境。Electron 能夠獲取到你定義在 package.json 中 main 文件內容,而後執行它。經過這個文件(一般咱們稱之爲 main.js),能夠建立一個應用窗口,這個應用窗口包含一個渲染好的 web 界面,還能夠和系統原生的 GUI 交互。html
具體來講,就是當你啓動了一個 Electron 應用,就有一個主進程(main process )被建立了。這條進程將負責建立出應用的 GUI(也就是應用的窗口),並處理用戶與這個 GUI 之間的交互。web
但直接啓動 main.js 是沒法顯示應用窗口的,在 main.js 中經過調用BrowserWindow模塊才能將使用應用窗口。而後每一個瀏覽器窗口將執行它們各自的渲染器進程( renderer process )。渲染器進程將會處理一個真正的 web 頁面(HTML + CSS + JavaScript),將頁面渲染到窗口中。鑑於 Electron 使用的是基於 Chrominum 的瀏覽器內核,你就不太須要考慮兼容的問題。json
const {app, BrowserWindow} = require('electron') const path = require('path') const url = require('url') // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let win function createWindow() { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, autoHideMenuBar: true }) // and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null }) } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.