electron实现桌面应用
1. 簡介
- 官網
- Electron是由GitHub開發,使用 JavaScript,HTML 和 CSS 構建跨平臺的桌面應用程序
- Electron 可以讓你使用純 JavaScript 調用豐富的原生 APIs 來創造桌面應用。你可以把它看作是專注于桌面應用
- 在PC端混合app開發中,nwjs和electron都是可選的方案,它們都是基于Chromium和Node的結合體, 而electron相對而言是更好的選擇方案,它的社區相對比較活躍,bug比較少,文檔先對利索簡潔。
- electron 相對來說比 nw.js 靠譜。有一堆成功的案例:Atom 編輯器 2. Slack (那個獨角獸公司)3. Visual Studio Code 4. WordPress 等等。。
- Node. js 的所有 內置模塊 都在Electron中可用, 第三方 node 模塊中也完全支持 (包括 原生模塊 )。
- Electron 還為開發原生桌面應用程序提供了一些額外的內置模塊。 某些模塊僅在主進程中可用, 有些僅在渲染進程 (web 頁) 中可用, 而有些在這兩個進程中都可以使用。
2. 五分鐘快速上手
2.1 安裝electron
- npm init
- cnpm I electron –S
- npx electron
2.2 配置為入口文件
{"name": "electron-demo","version": "1.0.0","description": "","main": "main.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "electron ."},"author": "","license": "ISC","dependencies": {"electron": "^8.3.0"} }2.3 創建main.js文件
const electron = require('electron')const app = electron.app app.on('ready', ()=>{new electron.BrowserWindow({width: 800,height: 300}) })2.4創建窗口
app.on('ready', ()=>{const mainWindow = new BrowserWindow({width: 800,height: 500})mainWindow.loadFile('./index.html') })3. 主進程和渲染進程
Electron 運行 package.json 的 main 腳本的進程被稱為主進程。 在主進程中運行的腳本通過創建web頁面來展示用戶界面。 一個 Electron 應用總是有且只有一個主進程。
由于 Electron 使用了 Chromium 來展示 web 頁面,所以 Chromium 的多進程架構也被使用到。 每個 Electron 中的 web 頁面運行在它的叫渲染進程的進程中。
在普通的瀏覽器中,web頁面無法訪問操作系統的原生資源。 然而 Electron 的用戶在 Node.js 的 API 支持下可以在頁面中和操作系統進行一些底層交互。
ctrl+shift+i打開渲染進程調試
app.on('ready', ()=>{const mainWindow = new BrowserWindow({width: 800,height: 500})mainWindow.loadFile('./index.html')const mainWindow2 = new BrowserWindow({width: 800,height: 500})mainWindow2.loadFile('./index2.html') })4. 自定義原生菜單
4.1 自定義菜單
const electron = require('electron')const { app, Menu } = electron const template = [{label: '文件',submenu: [{label: '新建窗口'}]},{label: '編輯',submenu: [{label: '新建窗口'}]} ] const menu = Menu.buildFromTemplate(template)Menu.setApplicationMenu(menu)4.2 給菜單定義點擊事件
1、點擊打開新窗口
submenu: [{label: '新建窗口',click: ()=>{const newMainWindow = new BrowserWindow({width: 300,height: 300})newMainWindow.loadFile('./new.html')}} ]2、點擊打開瀏覽器
const { BrowserWindow, Menu, shell } = require('electron') const template = [{label: '文件',submenu: [{label: '文件1',click () {// 點擊打開新窗口const mainWindow2 = new BrowserWindow({width: 600,height: 600})mainWindow2.loadFile('./index.html')}}]},{label: 'csdn',click () {// 點擊打開瀏覽器shell.openExternal('https://www.csdn.net/')}} ]4.3 抽離菜單定義
const { BrowserWindow, Menu} = require('electron') const template = [{label: '文件',submenu: [{label: '新建窗口',click: ()=>{const newMainWindow = new BrowserWindow({width: 300,height: 300})newMainWindow.loadFile('./new.html')}}]},{label: '編輯',submenu: [{label: '新建窗口'}]} ] const menu = Menu.buildFromTemplate(template)Menu.setApplicationMenu(menu) require('./menu')打開調式
mainWindow.webContents.openDevTools()
4.4 自定義頂部菜單
-
通過frame創建無邊框窗口
const mainWindow = new electron.BrowserWindow({frame: false }) -
自定義窗口
<div class="header" style="-webkit-app-region: drag;"></div> -
icon
const mainWindow = new electron.BrowserWindow({width: 1000,height: 600,webPreferences: {nodeIntegration: true},frame: false,icon: './hm.ico'}) -
backgroundColor
4.5 定義右鍵菜單
js>index.js
const { remote } = require('electron') const template = [{label: '粘貼'},{label: '賦值'} ] const menu = remote.Menu.buildFromTemplate(template)window.addEventListener('contextmenu', (e) => {console.log(123)e.preventDefault()menu.popup({ window: remote.getCurrentWindow() }) })在index.html中引入
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><button>打開新的窗口</button><script src="./js/index.js"></script> </body> </html>能夠在html中使用node方法
const mainWindow = new BrowserWindow({width: 800,height: 500,webPreferences: {nodeIntegration: true} })4.6 點頁面打開瀏覽器
-
html
<a id="a1" href="https://blog.csdn.net/weixin_41819098">打開瀏覽器</a> -
js
const { shell } = require('electron') const allA = document.querySelectorAll('a')allA.forEach(item => {item.onclick = function (e) {e.preventDefault()console.log(item)shell.openExternal(item.href)} })
5. 自動刷新頁面
-
安裝插件
cnpm install --save-dev electron-reloader -
在入口引入插件
const reloader = require('electron-reloader') reloader(module,{})
6. 拖拽文件進行讀取
-
定義拖拽到指定區域
<div id="drop"> </div> #drop {width: 300px;height: 500px;background: hotpink; } -
添加拖拽事件獲取文件路徑
// 添加拖拽 const dropEl = document.querySelector('#drop') dropEl.addEventListener('drop', function(e) {if(e.dataTransfer.files.length === 1) {const filePath = e.dataTransfer.files[0].path} })dropEl.addEventListener('dragover', function (e) {e.preventDefault() }) -
引入fs模塊進行讀取
const fs = require('fs')// 添加拖拽 const dropEl = document.querySelector('#drop') dropEl.addEventListener('drop', function(e) {if(e.dataTransfer.files.length === 1) {const filePath = e.dataTransfer.files[0].pathconst fileContent = fs.readFileSync(filePath).toString()this.innerText = fileContent} })dropEl.addEventListener('dragover', function (e) {e.preventDefault() })
7. 打開對話框
7.1 讀取文件
-
定義點擊事件
<button onclick="openFile()">打開</button> -
定義事件函數
// 打開對話框 function openFile() {const res = remote.dialog.showOpenDialogSync({title: '選擇文件',buttonLabel: '哈哈',filters: [{ name: 'Custom File Type', extensions: ['js','html','json'] },]})const fileContent = fs.readFileSync(res[0]).toString()dropEl.innerText = fileContent }
7.2 保存文件
-
定義點擊事件
<button onclick="saveFile()">保存</button> -
事件函數
// 保存對話框 function saveFile() {const res = remote.dialog.showSaveDialogSync({title: '保存文件',buttonLabel: '保存文件',filters: [{ name: 'index', extensions: ['js'] },]})fs.writeFileSync(res, 'hahhdasdshafsdahjk') }
8. 消息提示
-
定義事件
<button onclick="messageBox()">提示</button> -
事件函數
// 提示信息 function messageBox() {remote.dialog.showMessageBoxSync({type: 'none',buttons: ['確定'],title: '提示消息',message: '明天會下雨呦'}) }
9. 定義快捷鍵
9.1 主線程定義
-
引入
const { app, BrowserWindow, globalShortcut } = require('electron') -
在ready中注冊快捷鍵
const { app, BrowserWindow, globalShortcut } = require('electron')
9.2 渲染進程定義
-
通過remote注冊
// 定義快捷鍵 remote.globalShortcut.register('Ctrl+O', () => {console.log('ctrl+o') }) -
定義快捷鍵最大、最小、關閉窗口
globalShortcut.register('Ctrl+T',()=>{mainWindow.unmaximize();})globalShortcut.register('Ctrl+H',()=>{mainWindow.close()})globalShortcut.register('Ctrl+M',()=>{mainWindow.maximize()})
10. 渲染進程和主線程通訊
-
定義按鈕
<div class="maxWindow no-drag" onclick="maxWindow()"></div> -
事件函數
function maxWindow() {ipcRenderer.send('max-window') } -
主線程定義事件
ipcMain.on('max-window', () => {mainWindow.maximize()}) -
傳參
let windowSize = 'unmax-window' function maxWindow() {windowSize = windowSize === 'max-window' ?'unmax-window':'max-window'ipcRenderer.send('max-window',windowSize) } -
接收參數
ipcMain.on('max-window', (event,arg) => {console.log(arg)if(arg === 'unmax-window') return mainWindow.maximize();mainWindow.unmaximize()}) -
通過isMaximized判斷當前窗口
11. 網絡請求
async function getMsg () {const res = await fetch('http://127.0.0.1:3006/api/person').then(res=>res.json())console.log(res) }12 .electron結合框架開發
12.1 結合react
利用react初始化項目
- npx create-react-app electron-react
- cd electron-react
- npm start
安裝electron
-
cnpm i electron
-
添加electron的任務
"main": "main.js", "scripts": {"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject","electron": "electron ."}, -
添加main.js https://github.com/electron/electron-quick-start/blob/master/main.js
const {app, BrowserWindow} = require('electron')function createWindow () {// Create the browser window.const mainWindow = new BrowserWindow({width: 800,height: 600})// Open the DevTools.// mainWindow.webContents.openDevTools() }app.whenReady().then(() => {createWindow() }) -
加載react項目
mainWindow.loadURL('http://localhost:3000/')
12.2 electron結合vue
同react
13 electron打包
-
將vue項目打包
-
修改electron引入的文件
mainWindow.loadFile('./dist/index.html') -
安裝electron-packager
"packager": "electron-packager ./ HelloWorld --platform=win32 --arch=x64 --out ./outApp --overwrite --icon=./favicon.ico"
總結
以上是生活随笔為你收集整理的electron实现桌面应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 区块链-DEFI产品
- 下一篇: C语言之生肖、年龄、星座查询