zoukankan      html  css  js  c++  java
  • 01.electron笔记: 基本知识

    electron

    资料

    开源地址:https://github.com/electron

    示例:https://github.com/electron/electron-quick-start

    文档:https://www.electronjs.org/docs

    教程:https://www.w3cschool.cn/electronmanual/wcx31ql6.html

    下载示例

    示例地址: https://github.com/electron/electron-quick-start

    使用git,执行:

    # Clone this repository
    git clone https://github.com/electron/electron-quick-start
    # Go into the repository
    cd electron-quick-start
    # Install dependencies
    npm install
    # Run the app
    npm start
    

    npm 出现的问题

    PS E:KzoneCodeLibelectronmuke-musicsrc> npm install
    
    > core-js@3.6.5 postinstall E:KzoneCodeLibelectronmuke-musicsrc
    ode_modulescore-js
    > node -e "try{require('./postinstall')}catch(e){}"
    
    Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
    
    The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
    > https://opencollective.com/core-js 
    > https://www.patreon.com/zloirock 
    
    Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
    
    
    > electron@9.0.2 postinstall E:KzoneCodeLibelectronmuke-musicsrc
    ode_moduleselectron
    > node install.js
    
    (一直卡在这里)
    
    

    解决方案

    使用cnpm

    • 安装淘宝的cnpm,然后在使用时直接将npm命令替换成cnpm命令即可
    npm install -g cnpm --registry=https://registry.npm.taobao.org
    

    运行 cnpm,出现问题:

    > cnpm -v
    cnpm : 无法加载文件 C:Users14196AppDataRoaming
    pmcnpm.ps1,因为在此系统上禁止运行脚本。
    

    解决:

    首先打开powershall (管理员身份运行)

    然后输入

    set-ExecutionPolicy RemoteSigned
    

    我们会看到:

    PS C:WINDOWSsystem32> set-ExecutionPolicy RemoteSigned>> 执行策略更改执行策略可帮助你防止执行不信任的脚本。更改执行策略可能会产生安全风险,如 https:/go.microsoft.com/fwlink/?LinkID=135170中的 about_Execution_Policies 帮助主题所述。是否要更改执行策略?[Y] 是(Y)  [A] 全是(A)  [N] 否(N)  [L] 全否(L)  [S] 暂停(S)  [?] 帮助 (默认值为“N”): Y 
    C:WINDOWSsystem32>
    
    • 运行

      1 cnpm install

      2 cnpm start

      √ Installed 1 packages
      √ Linked 82 latest versions
      [1/2] scripts.postinstall electron@9.0.2 › @electron/get@1.12.2 › global-agent@2.1.12 › core-js@^3.6.5 run "node -e "try{require('./postinstall')}catch(e){}"", root: "E:\Kzone\CodeLib\electron\muke-music\src\node_modules\_core-js@3.6.5@core-js"
      Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
      
      The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
      > https://opencollective.com/core-js
      > https://www.patreon.com/zloirock
      
      Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
      
      [1/2] scripts.postinstall electron@9.0.2 › @electron/get@1.12.2 › global-agent@2.1.12 › core-js@^3.6.5 finished in 194ms
      [2/2] scripts.postinstall electron@^9.0.2 run "node install.js", root: "E:\Kzone\CodeLib\electron\muke-music\src\node_modules\_electron@9.0.2@electron"
      [2/2] scripts.postinstall electron@^9.0.2 finished in 2s
      √ Run 2 scripts
      Recently updated (since 2020-05-31): 3 packages (detail see file E:KzoneCodeLibelectronmuke-musicsrc
      ode_modules.recently_updates.txt)
      √ All packages installed (87 packages installed from npm registry, used 5s(network 2s), speed 91.18kB/s, json 83(226.59kB), tarball 0B)
      PS E:KzoneCodeLibelectronmuke-musicsrc> cnpm start
      
      > electron-quick-start@1.0.0 start E:KzoneCodeLibelectronmuke-musicsrc
      > electron .
      

    第一个electron 应用

    项目结构

    • package.json - Points to the app's main file and lists its details and dependencies.
    • main.js - Starts the app and creates a browser window to render HTML. This is the app's main process.
    • index.html - A web page to render. This is the app's renderer process.

    项目详解:https://www.jianshu.com/p/6fdfac66b964

    package.json

    {
      "name": "electron-music",
      "version": "1.0.0",
      "description": "A Electron Music App",
      "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
    
      "devDependencies": {
        "electron": "^9.0.2"
      }
    }
    

    main.js

    // Modules to control application life and create native browser window
    const {app, BrowserWindow} = require('electron')
    const path = require('path')
    
    function createWindow () {
      // Create the browser window.
      const mainWindow = new BrowserWindow({
         800,
        height: 600,
        webPreferences: {
          nodeIntegration:true
        }
      })
    
      // and load the index.html of the app.
      mainWindow.loadFile('index.html')
    
      // Open the DevTools.
      // mainWindow.webContents.openDevTools()
    }
    
    // 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()
      
      app.on('activate', function () {
        // 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
      })
    })
    
    // Quit when all windows are closed.
    app.on('window-all-closed', function () {
      // 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()
    })
    
    // 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.
    
    

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Hello World!</title>
      </head>
      <body>
        <h1>Hello World!</h1>
        <script src="./renderer.js"></script>
      </body>
    </html>
    
    

    renderer.js

    alert(process.versions.node)
    window.addEventListener("DOMContentLoaded", ()=>{
        alert("DOMContentLoaded")
    });
    
    

    主进程(Main Process)

    Electron 运行 package.jsonmain 脚本的进程被称为主进程

    • 可以使用和系统对接的Electron Api,比如:创建菜单,上传文件

    • 创建渲染进程(Renderder Process)

    • 全面支持 Node.js

    • 只有一个,作为整个程序的入口点( 一个 Electron 应用总是有且只有一个主进程。)

    渲染进程 (Renderder Process)

    • 可以有多个,每个对应一个窗口

    • 每个都是一个单独的进程

    • 全面支持Node.js 和Dom API

    • 可以使用一部分 Electron 提供的API

    主进程和渲染进程之间的区别

    主进程使用 BrowserWindow 实例创建页面。 每个 BrowserWindow 实例都在自己的渲染进程里运行页面。 当一个 BrowserWindow 实例被销毁后,相应的渲染进程也会被终止。

    主进程管理所有的web页面和它们对应的渲染进程。 每个渲染进程都是独立的,它只关心它所运行的 web 页面。

    在页面中调用与 GUI 相关的原生 API 是不被允许的,因为在 web 页面里操作原生的 GUI 资源是非常危险的,而且容易造成资源泄露。 如果你想在 web 页面里使用 GUI 操作,其对应的渲染进程必须与主进程进行通讯,请求主进程进行相关的 GUI 操作。

    进程间通信

    Electron为主进程( main process)和渲染器进程(renderer processes)通信提供了多种实现方式,如

    可以使用ipcRendereripcMain模块发送消息,

    使用 remote模块进行RPC方式通信。

    IPC进程间通信

    ipcMain

    • 发送数据 ipcMain.send()
    • 接收数据 ipcMain.on()

    ipcRenderer

    • 发送数据 ipcRenderer.send()

    • 接收数据 ipcRenderer.on()

      示例

    • 渲染进程renderer.js

      const {ipcRenderer} = require('electron')
      
      window.addEventListener("DOMContentLoaded", ()=>{
          ipcRenderer.send("message", "msg from renderer!!!")
          ipcRenderer.on("reply", (event, arg) =>{
              //console.log(arg);
              alert(arg);
          })
      });
      
      • 发送数据 ipcRenderer.send()
      • 接收数据 ipcRenderer.on()
    • main.js

      const {app, BrowserWindow, ipcMain} = require('electron')
      
      app.whenReady().then(() => {
        createWindow()
        ...
      
        ipcMain.on("message", (event, arg) =>{ //接收数据
          console.log(arg);
          event.sender.send("reply", "msg from main.js"); //发送数据
          //mainWindow.send("reply", "msg from main.js");
        })
      
      })
      
    • 发送数据 ipcMain.send()

    • 接收数据 ipcMain.on()

  • 相关阅读:
    php去除字符串(空格,换行,反斜杠)
    周末撸了个Excel框架,现已开源,yyds!!
    Python基础之pytest参数化
    解决 remote: HTTP Basic: Access denied Authentication failed for 'https://'报错
    删除上传 github 中的 .idea 文件夹
    Nacos配置管理最佳实践
    痞子衡嵌入式:在IAR开发环境下将整个源文件代码重定向到任意RAM中的方法
    痞子衡嵌入式:我入选了2021年度与非网(eefocus)星选创作者Top10
    《痞子衡嵌入式半月刊》 第 47 期
    重新iviewUI Modal 组件 ok事件默认直接关闭modal 的行为[Code Snippet]
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/13060958.html
Copyright © 2011-2022 走看看