webview的API:点击查看
在渲染进程中,内嵌了一个webview,webview想要跟渲染进程,或者跟主进程应该怎么通讯,网上有类似文章,但是写的都不详细,electron官网上也有介绍使用ipc-meesage来通讯的,但是并没有介绍的很详细,也尝试过executeJavaScript来给webview注入JS,来传递数据给webview,但这样webview没法发送数据给渲染进程、主进程。
下面详细介绍
最关键的部分webview的 preload,很多同学会卡在这里,不知道怎么添加preload的路径,附正确姿势
preload.js
逻辑很简单,就把electron挂载到window上
import path from 'path'
import { platform } from 'process'
import electron from 'electron'
window.electron = electron
window.platform = platform
window.preload = path.join(__dirname, 'preload.js')
主进程(background.js)
给global添加个变量preloadPath
const globalData: any = global globalData.preloadPath = path.join(__dirname, 'preload.js') //preload.js跟主进程文件background.js同级
渲染进程
const { remote } = require('electron')
const preloadPath= remote.getGlobal('preloadPath')
//webpreference可以根据需要自己配置,这里关注preload的引入方式
给webview绑定监听事件
this.$nextTick(() => {
const webview = document.querySelector('webview') as any
this.webview = webview
if (webview) {
webview.addEventListener('dom-ready', () => {
this.loading = false
webview.openDevTools()
})
webview.addEventListener('ipc-message', this.onIpcMessage)//接收到webview过来的消息
}
})
onIpcMessage(event: any) {//处理webview发送过来的消息
const { channel, args } = event
console.log(channel, args )
// 处理完消息后再发送给webview
this.webview.send(channel, 'hahah') //这里随便发个hahah给webview
}
webview页面
(假装是上面的baidu.com,总之是非electron内的项目,可以是你自己的web项目)
通过上面正确的配置preload,webview页面已经能通过window.electron访问到electron实例了
发消息给webview所在渲染进程:
const ipcRenderer = window.electron.ipcRenderer
ipcRenderer.sendToHost('testChannel', 111) //testChannel为渲染进程处理ipc-message里的channel,发送的数据为111
ipcRenderer.on("testChannel", (event: Event, result: any) => {
console.log(result)//这里result为hahah
})
发消息给主进程
就用ipcRenderer.send()
Web前端(W3Cways.com) - Web前端学习之路