Shu-How Zの小窝

Loading...

Electron超详细实战开发教程

Electron超详细实战开发教程

Electron入门:https://www.bilibili.com/video/BV1QB4y1F722

1 2

00-最新Electron课程介绍

Electron e lai 纯 / iao 凑

01-electron介绍与第一个应用

https://www.electronjs.org/

electron

github.com/electron/electron-quick-start


02-使用yarn快速创建electron项目

electronforge.io

yarn create electron-app my-app
上面旧

npx create-electron-app@latest my-app
npm run make

03-渲染进程的node环境调用
04-实现拖动文件渲染在页面中

05-webview的操控和使用

index,html
 <webview id="wv" src="http://www.bilibili.com" style="width:100%;height:400px;"></webview>


index.js 主进程
const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 浏览器的js可以支持node接口
      nodeIntegration: true,
      contextIsolation:false,
      // 支持webview
      webviewTag:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

    <webview>.insertCSS(css
    <webview>.executeJavaScript(code[, userGesture])                    

https://www.electronjs.org/docs/latest/api/webview-tag

06-主进程和渲染进程的通讯

-主进程 index.js
const { app, BrowserWindow,ipcMain} = require('electron');
const path = require('node:path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

// 监听渲染进程发送过来的1c-message事件
ipcMain.on('1c-message',(event,arg)=>{
  // 回复渲染进程
  event.reply('1c-reply','这是主进程回复的消息');
  console.log(arg);
})


ipcMain.on('openNewWindow',(event,arg)=>{
  cWindow('http://www.baidu.com');
})

const cWindow = (url) => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 浏览器的js可以支持node接口
      nodeIntegration: true,
      contextIsolation:false,
      // 支持webview
      webviewTag:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  mainWindow.loadURL(url || 'http://www.bilibili.com');

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  
};

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 浏览器的js可以支持node接口
      nodeIntegration: true,
      contextIsolation:false,
      // 支持webview
      webviewTag:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));


  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  setTimeout(() => {
    // 主动的发消息给渲染进程
    mainWindow.webContents.send('lc-active','创建窗口之后,主进程主动发送数据给到渲染进程');
  }, 2000);
  
};

// 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.whenReady().then(() => {
  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 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 import them here.


渲染进程-index.html
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button id="btn">点击</button>
    <h1>💖 Hello World!</h1>
    <p>Welcome to your Electron application.</p>
    <webview id="wv" src="http://www.bilibili.com" style="width:100%;height:400px;"></webview>
  </body>
  <script src="js/render.js"></script>
  <script>
    let {ipcRenderer} = require('electron');
    ipcRenderer.on('lc-active',(event,arg)=>{
      console.log(event);
      console.log(arg);
    })
    // 主动发送消息给主进程
    ipcRenderer.send('lc-message','子进程给主进程发送数据');
    ipcRenderer.on('lc-reply',(event,arg)=>{
      console.log(event);
      console.log(arg);
    })

    let btn = document.getElementById('btn');
    btn.addEventListener('click',()=>{
      ipcRenderer.send('openNewWindow');
    })
  </script>
</html>

07-dialog窗口的配置

index.js

const { app, BrowserWindow,ipcMain,dialog} = require('electron');

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 浏览器的js可以支持node接口
      nodeIntegration: true,
      contextIsolation:false,
      // 支持webview
      webviewTag:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));


  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  setTimeout(() => {
    // openFile允许选择文件
    // openDirectory允许选择文件夹
    // multiSelection允许多选
    // showHiddenFiles显示隐藏文件
    // createDirectory允许创建文件夹
    dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
    }).then(result=>{
      console.log(result.filePaths);
      console.log(result.canceled);
    })
  }, 2000);

  mainWindow.on('close',(e)=>{
    e.preventDefault();
    dialog.showMessageBox(mainWindow,{
      type:'warning',
      buttons:['否','是',],
      title:'提示',
      message:'你确定要关闭吗?'
    }).then(result=>{
      if(result.response == 1){
        app.exit();
      }
    })
  })
};

08-原生自带网络请求的库

index.js
const { app, BrowserWindow,ipcMain,dialog,net} = require('electron');
const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 浏览器的js可以支持node接口
      nodeIntegration: true,
      contextIsolation:false,
      // 支持webview
      webviewTag:true,
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));


  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  let request=net.request('https://www.bilibili.com');
  request.on('response',(response)=>{
    console.log(`状态码: ${response.statusCode}`);
    response.on('data',(chunk)=>{
      console.log(`响应主体: ${chunk.toString()}`);
    })
  })
  request.end();
};

09-electron-vue的环境搭建

simulatedgreg.gitbooks.io/electron-vue/content/cn/

# 安装 vue-cli 和 脚手架样板代码
npm install -g vue-cli
vue init simulatedgreg/electron-vue my-project

安装的是vue2.x

# 安装依赖并运行你的程序
cd my-project
yarn # 或者 npm install
yarn run dev # 或者 npm run dev

10-项目的基本结构和使用

11-electron使用AntdUI组件

https://antdv.com/docs/vue/introduce-cn/

vue2.x
https://1x.antdv.com/docs/vue/getting-started-cn/



12-实现查找书籍功能

shiyisoushu.com/search/说话

时宜搜书

https://www.shiyisoushu.com/api/search/v3?q=

13-解决rowKey报错和获取下载链接地址

14-修改Axios实现后端请求

responseType:'stream'
axios配置以流形式下载

15-优化页面和功能
16-创建books页面和路由
17-解析EPUB文件

npm install epub --save

18-根据磁盘电子书生成书库列表

//将二进制buffer数据转化成图片地址base64 img

this.$forceUpdate()强制更新

19-通过路由传参将书籍内容传递过去
20-电子生成书章节列表
21-获取图片解析到书籍里

npm i cheerio

22-解析epub的css内容渲染到书籍里
23-修改中文不能搜索bug和打包成软件

posted @ 2026-04-29 19:20  KooTeam  阅读(10)  评论(0)    收藏  举报