electron教程-API介绍

一、app:控制应用程序的事件生命周期。https://www.electronjs.org/zh/docs/latest/api/app 

  • ready事件:通常我们使用触发器的 .on 函数来监听 Node.js 事件。
    但是 Electron 暴露了 app.whenReady() 方法,作为其 ready 事件的专用监听器,这样可以避免直接监听 .on 事件带来的一些问题。
  • window-all-closed事件:
  • activate事件:(macOS才用的事件,类似ready事件)

二、BrowserWindow 类:创建并控制浏览器窗口。https://www.electronjs.org/zh/docs/latest/api/browser-window 

  在 app 模块 emitted ready 事件之前,您不能使用此模块。

// 在主进程中.
const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ width: 800, height: 600 })

// Load a remote URL
win.loadURL('https://github.com')

// Or load a local HTML file
win.loadFile('index.html')

  注意:实例窗口加载 页面 有两个中加载方式,loadURL 和 loadFile

  • loadURL:这个是通过url加载 服务器上的静态资源。可以是 http协议,也可以是 file协议
    win.loadURL('http://www.baidu.com');
    // 或 加载本地文件,通过file协议
    win.loadURL(`file://${__dirname}/index.html`);  // 虽然 loadURL 在没有 给定协议时,会默认添加上 file 协议。但还是建议主动添加上。
  • loadFile:加载本地html文件,会自动再前面添加上 "file://" 协议。 不能自己加上file:// 协议
     win.loadFile(`${__dirname}/src/index.html`);

三、进程间通信(IPC 通道):https://www.electronjs.org/zh/docs/latest/tutorial/ipc

  •  进程通信的模块:
    • ipcMain:从主进程到渲染进程的异步通信。
    • ipcRenderer:从渲染器进程到主进程的异步通信。
  • 模式 1:渲染器进程到主进程(单向)
    1. 使用 ipcMain.on 监听事件
    2. 通过预加载脚本暴露 ipcRenderer.send
      默认情况下,渲染器进程没有权限访问 Node.js 和 Electron 模块。 作为应用开发者,您需要使用 contextBridge API 来选择要从预加载脚本中暴露哪些 API。
      const { contextBridge, ipcRenderer } = require('electron')
      
      contextBridge.exposeInMainWorld('electronAPI', {
          setTitle: (title) => ipcRenderer.send('set-title', title)
      })
    3. 渲染器进程直接调用 预加载脚本暴露出来的API。
      window.electronAPI.setTitle(title)  // 预加载暴露的 electronAPI.setTitle
  •  模式 2:渲染器进程到主进程(双向)
    双向 IPC 的一个常见应用是从渲染器进程代码调用主进程模块并等待结果。 这可以通过将 ipcRenderer.invoke 与 ipcMain.handle 搭配使用来完成。
    1. 使用 ipcMain.handle 监听事件
    2. 通过预加载脚本暴露 ipcRenderer.invoke
      const { contextBridge, ipcRenderer } = require('electron')
      
      contextBridge.exposeInMainWorld('electronAPI', {
        openFile: () => ipcRenderer.invoke('dialog:openFile')
      })
    3. 渲染器进程直接调用 预加载脚本暴露出来的API。
      async () => {
        const filePath = await window.electronAPI.openFile()
        filePathElement.innerText = filePath
      }
  •  模式 3:主进程到渲染器进程
    1. 使用 webContents 模块发送消息
    2. 通过预加载脚本暴露 ipcRenderer.on
      const { contextBridge, ipcRenderer } = require('electron')
      
      contextBridge.exposeInMainWorld('electronAPI', {
          onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback)
      })
    3. 渲染器进程 接收 信息
      const counter = document.getElementById('counter')
      
      window.electronAPI.onUpdateCounter((_event, value) => {
          const oldValue = Number(counter.innerText)
          const newValue = oldValue + value
          counter.innerText = newValue
      })

      对于从主进程到渲染器进程的 IPC,没有与 ipcRenderer.invoke 等效的 API。 不过,您可以从 ipcRenderer.on 回调中将回复发送回主进程。

  •  模式 4:渲染器进程到渲染器进程

 

posted @ 2022-01-18 16:03  吴飞ff  阅读(741)  评论(0编辑  收藏  举报