Electron主进程与渲染进程通信,webview与其加载页间的通信

1. 进程间通信

进程间通信使用 ipcMain与ipcRenderer模块

主进程:

const ipcMain =require('electron').ipcMain;

ipcMain.on('message',function(event, arg) {//监听渲染进程发送的message

        console.log(arg);// prints "ping"

        event.sender.send('reply', 'pong');//event.sender获取事件的发送者,并发送reply事件,‘pong’为发送的数据

});

渲染进程:

const ipcRenderer =require('electron').ipcRenderer;

ipcRenderer.send('message', 'ping');

ipcRenderer.on('reply', function(event, arg) {console.log(arg);// prints "pong"}); //监听reply

在主进程也可以使用以下方式发送消息:mainWindow.webContents.send('saveMessage','delect',index,innerIndex)

webContents从主进程向渲染进程发送消息

主进程:

var window=null;

app.on('ready',function(){

    window=new BrowserWindow({width:800, height:600});

    window.loadURL('file://'+ __dirname +'/index.html');

    window.webContents.on('did-finish-load',function(){

        window.webContents.send('ping', 'whoooooooh!'); //主进程发送消息ping

     });

});

渲染进程:

require('electron').ipcRenderer.on('ping', function(event, message) {//监听ping事件

      console.log(message);  // "whoooooooh!"  

  });

2. 使用webview控件加载页面时,webview所在页面与被加载页面间的通信

webview所有的方法必须在加载完成之后才能使用,如下:

webview所在页面

const webview = document.querySelector('webview')

   webview.addEventListener('dom-ready', () => {

          webview.openDevTools()

    })

使用send()方法发送消息webview.send('start') //发送start,同上面的wenContents的send()方法

在被webview加载的页面里

可以通过 ipcRenderer 模块去监听channel 事件,从而处理发过来的这些信息

const {ipcRenderer} = require('electron')

ipcRenderer.on('start', (ev) => {//监听start

            console.log(ev)

        })

$('#sendBT').click(function() {

            ipcRenderer.sendToHost('ztree') //向webview所在页面发送消息

  })

 注意://ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...]),它的事件将发往 host page 的 webview 元素,而不是主进程.

//在webview所在页面使用 webview.addEventListener('ipc-message',(event)=>{})监听被加载特免传送的消息

webview.addEventListener('ipc-message', (event) => { //ipc-message监听,被webview加载页面传来的信息

           console.log(event.channel)

 })


参考链接:https://www.jianshu.com/p/cc1142207040
 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值