1. 程式人生 > 實用技巧 >electron熟悉主程序和渲染程序通訊 ipcRenderer.send() and ipcMain.to()

electron熟悉主程序和渲染程序通訊 ipcRenderer.send() and ipcMain.to()

在昨天的時候,已經用過ipcRendered.sendSync(), 昨天的程式碼是這樣的

renderer.js檔案

constele_sendbtn=document.getElementById("send_btn") ele_sendbtn.onclick=function(){  console.log("thisisrendereroutputlog",ipcRenderer.sendSync('synchronous-message',datas)) //同步處理 alert(datas) } main.js 檔案中 ipcMain.on('synchronous-message',function(event,arg){ console.log(arg); event.returnValue="XXX";
}); 主程序和渲染程序通訊成功,如下圖

今天又寫了一個是這樣的(搞了好久才搞明白,同步非同步 處理是不一樣的,這是非同步處理)

以下程式碼是已更正後的結果

renderer.js 如下:

submit.onclick=function(e){
letdata=ele_filepath.files[0].path; console.log(data); ipcRenderer.send('uploadFile',data)
} main.js 如下: ipcMain.on('uploadFile',(event,arg)=>{ console.log("filePath:",arg); //event.returnValue={msg:'OK', //code:0} event.sender.send('uploadFileSuccess',{
msg:'OK', code:0 }) })

官網API連結:https://www.electronjs.org/docs/api/ipc-main#ipcmainhandleoncechannel-listener

劃重點:

  • When sending a message, the event name is thechannel.
  • To reply to a synchronous message, you need to setevent.returnValue.
  • To send an asynchronous message back to the sender, you can useevent.reply(...)
    . This helper method will automatically handle messages coming from frames that aren't the main frame (e.g. iframes) whereasevent.sender.send(...)will always send to the main frame.

PS: 如果能耐心的看完這段話,我就不會被坑了小1天的時間,教訓呀