electron实现桌面应用
1. 簡(jiǎn)介
- 官網(wǎng)
- Electron是由GitHub開(kāi)發(fā),使用 JavaScript,HTML 和 CSS 構(gòu)建跨平臺(tái)的桌面應(yīng)用程序
- Electron 可以讓你使用純 JavaScript 調(diào)用豐富的原生 APIs 來(lái)創(chuàng)造桌面應(yīng)用。你可以把它看作是專注于桌面應(yīng)用
- 在PC端混合app開(kāi)發(fā)中,nwjs和electron都是可選的方案,它們都是基于Chromium和Node的結(jié)合體, 而electron相對(duì)而言是更好的選擇方案,它的社區(qū)相對(duì)比較活躍,bug比較少,文檔先對(duì)利索簡(jiǎn)潔。
- electron 相對(duì)來(lái)說(shuō)比 nw.js 靠譜。有一堆成功的案例:Atom 編輯器 2. Slack (那個(gè)獨(dú)角獸公司)3. Visual Studio Code 4. WordPress 等等。。
- Node. js 的所有 內(nèi)置模塊 都在Electron中可用, 第三方 node 模塊中也完全支持 (包括 原生模塊 )。
- Electron 還為開(kāi)發(fā)原生桌面應(yīng)用程序提供了一些額外的內(nèi)置模塊。 某些模塊僅在主進(jìn)程中可用, 有些僅在渲染進(jìn)程 (web 頁(yè)) 中可用, 而有些在這兩個(gè)進(jìn)程中都可以使用。
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 創(chuàng)建main.js文件
const electron = require('electron')const app = electron.app app.on('ready', ()=>{new electron.BrowserWindow({width: 800,height: 300}) })2.4創(chuàng)建窗口
app.on('ready', ()=>{const mainWindow = new BrowserWindow({width: 800,height: 500})mainWindow.loadFile('./index.html') })3. 主進(jìn)程和渲染進(jìn)程
Electron 運(yùn)行 package.json 的 main 腳本的進(jìn)程被稱為主進(jìn)程。 在主進(jìn)程中運(yùn)行的腳本通過(guò)創(chuàng)建web頁(yè)面來(lái)展示用戶界面。 一個(gè) Electron 應(yīng)用總是有且只有一個(gè)主進(jìn)程。
由于 Electron 使用了 Chromium 來(lái)展示 web 頁(yè)面,所以 Chromium 的多進(jìn)程架構(gòu)也被使用到。 每個(gè) Electron 中的 web 頁(yè)面運(yùn)行在它的叫渲染進(jìn)程的進(jìn)程中。
在普通的瀏覽器中,web頁(yè)面無(wú)法訪問(wèn)操作系統(tǒng)的原生資源。 然而 Electron 的用戶在 Node.js 的 API 支持下可以在頁(yè)面中和操作系統(tǒng)進(jìn)行一些底層交互。
ctrl+shift+i打開(kāi)渲染進(jìn)程調(diào)試
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 給菜單定義點(diǎn)擊事件
1、點(diǎn)擊打開(kāi)新窗口
submenu: [{label: '新建窗口',click: ()=>{const newMainWindow = new BrowserWindow({width: 300,height: 300})newMainWindow.loadFile('./new.html')}} ]2、點(diǎn)擊打開(kāi)瀏覽器
const { BrowserWindow, Menu, shell } = require('electron') const template = [{label: '文件',submenu: [{label: '文件1',click () {// 點(diǎn)擊打開(kāi)新窗口const mainWindow2 = new BrowserWindow({width: 600,height: 600})mainWindow2.loadFile('./index.html')}}]},{label: 'csdn',click () {// 點(diǎn)擊打開(kāi)瀏覽器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')打開(kāi)調(diào)式
mainWindow.webContents.openDevTools()
4.4 自定義頂部菜單
-
通過(guò)frame創(chuàng)建無(wú)邊框窗口
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>打開(kāi)新的窗口</button><script src="./js/index.js"></script> </body> </html>能夠在html中使用node方法
const mainWindow = new BrowserWindow({width: 800,height: 500,webPreferences: {nodeIntegration: true} })4.6 點(diǎn)頁(yè)面打開(kāi)瀏覽器
-
html
<a id="a1" href="https://blog.csdn.net/weixin_41819098">打開(kāi)瀏覽器</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. 自動(dòng)刷新頁(yè)面
-
安裝插件
cnpm install --save-dev electron-reloader -
在入口引入插件
const reloader = require('electron-reloader') reloader(module,{})
6. 拖拽文件進(jìn)行讀取
-
定義拖拽到指定區(qū)域
<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模塊進(jìn)行讀取
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. 打開(kāi)對(duì)話框
7.1 讀取文件
-
定義點(diǎn)擊事件
<button onclick="openFile()">打開(kāi)</button> -
定義事件函數(shù)
// 打開(kāi)對(duì)話框 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 保存文件
-
定義點(diǎn)擊事件
<button onclick="saveFile()">保存</button> -
事件函數(shù)
// 保存對(duì)話框 function saveFile() {const res = remote.dialog.showSaveDialogSync({title: '保存文件',buttonLabel: '保存文件',filters: [{ name: 'index', extensions: ['js'] },]})fs.writeFileSync(res, 'hahhdasdshafsdahjk') }
8. 消息提示
-
定義事件
<button onclick="messageBox()">提示</button> -
事件函數(shù)
// 提示信息 function messageBox() {remote.dialog.showMessageBoxSync({type: 'none',buttons: ['確定'],title: '提示消息',message: '明天會(huì)下雨呦'}) }
9. 定義快捷鍵
9.1 主線程定義
-
引入
const { app, BrowserWindow, globalShortcut } = require('electron') -
在ready中注冊(cè)快捷鍵
const { app, BrowserWindow, globalShortcut } = require('electron')
9.2 渲染進(jìn)程定義
-
通過(guò)remote注冊(cè)
// 定義快捷鍵 remote.globalShortcut.register('Ctrl+O', () => {console.log('ctrl+o') }) -
定義快捷鍵最大、最小、關(guān)閉窗口
globalShortcut.register('Ctrl+T',()=>{mainWindow.unmaximize();})globalShortcut.register('Ctrl+H',()=>{mainWindow.close()})globalShortcut.register('Ctrl+M',()=>{mainWindow.maximize()})
10. 渲染進(jìn)程和主線程通訊
-
定義按鈕
<div class="maxWindow no-drag" onclick="maxWindow()"></div> -
事件函數(shù)
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) } -
接收參數(shù)
ipcMain.on('max-window', (event,arg) => {console.log(arg)if(arg === 'unmax-window') return mainWindow.maximize();mainWindow.unmaximize()}) -
通過(guò)isMaximized判斷當(dāng)前窗口
11. 網(wǎng)絡(luò)請(qǐng)求
async function getMsg () {const res = await fetch('http://127.0.0.1:3006/api/person').then(res=>res.json())console.log(res) }12 .electron結(jié)合框架開(kāi)發(fā)
12.1 結(jié)合react
利用react初始化項(xiàng)目
- npx create-react-app electron-react
- cd electron-react
- npm start
安裝electron
-
cnpm i electron
-
添加electron的任務(wù)
"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項(xiàng)目
mainWindow.loadURL('http://localhost:3000/')
12.2 electron結(jié)合vue
同react
13 electron打包
-
將vue項(xiàng)目打包
-
修改electron引入的文件
mainWindow.loadFile('./dist/index.html') -
安裝electron-packager
"packager": "electron-packager ./ HelloWorld --platform=win32 --arch=x64 --out ./outApp --overwrite --icon=./favicon.ico"
總結(jié)
以上是生活随笔為你收集整理的electron实现桌面应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 区块链-DEFI产品
- 下一篇: C语言之生肖、年龄、星座查询