【electron】学习(三)

主进程与渲染进程

在这里插入图片描述
通常可以知道index.js文件在electron中是放置主进程的,比如打开界面的大小等等;渲染进程可以看到是主要是放置渲染的东西,所以大致是index.html文件。

ipcMain和ipcRender用于主进程与渲染进程的沟通

chcp 665001 是控制终端返回数据的编码utf-8
在这里插入图片描述

主进程与渲染进程(单向)

一、没使用preload的情况

index.js主进程实现
ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
    console.log(title)
    console.log(1111111)
  })
index.html渲染进程实现
ipcRenderer.send('set-title', '收到主进程')
console.log(1111111,title)

如果更好的实现上下进程通信,可以通过preload.js文件对上下进程进行处理

二、使用preload的情况

index.js主进程实现
ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
    console.log(title)//后台会报“收到主进程”的信息
    console.log(1111111)
  })
index.html渲染进程实现
window.setTitleApi.firstApi('收到主进程')
console.log(1111111,title)
preload.js实现上下文隔离进程
let { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('setTitleApi', {
firstApi: (title) => {
  ipcRenderer.send('set-title', title)
  console.log('33333333', title)
}
})

主进程与渲染进程(双向)

 在主进程中,我们将创建一个 handleFileOpen() 函数,它调用 dialog.showOpenDialog 并返回用户选择的文件路径值。 每当渲染器进程通过 dialog:openFile 通道发送 ipcRender.invoke 消息时,此函数被用作一个回调。 然后,返回值将作为一个 Promise 返回到最初的 invoke 调用。
// 渲染进程
ipcRenderer.invoke('some-name', someArgument).then((result) => {
  // ...
})

// 主进程
ipcMain.handle('some-name', async (event, someArgument) => {
  const result = await doSomeWork(someArgument)
  return result
})
API: dialog事件

显示用于打开和保存文件、警报等的本机系统对话框。

const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))
1. main.js监听事件
const { BrowserWindow, dialog, ipcMain } = require('electron')
async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog()
  if (canceled) {
    return
  } else {
    return filePaths[0]
  }
}

function createWindow () {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  setTimeout(()=>{
   ipcMain.handle('dialog:openFile', handleFileOpen)
  }, 2000)
  mainWindow.loadFile('index.html')
}
2.preload.js上下进程
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
  openFile: () => ipcRenderer.invoke('dialog:openFile')
})
3.index.html渲染进程
const btn = document.getElementById('btn')
const filePathElement = document.getElementById('filePath')

btn.addEventListener('click', async () => {
  const filePath = await window.electronAPI.openFile()
  filePathElement.innerText = filePath
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值