electron熟悉主程序和渲染程序通訊 ipcRenderer.send() and ipcMain.to()
阿新 • • 發佈:2020-07-23
在昨天的時候,已經用過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',{
官網API連結:https://www.electronjs.org/docs/api/ipc-main#ipcmainhandleoncechannel-listener
劃重點:
- When sending a message, the event name is the
channel
. - To reply to a synchronous message, you need to set
event.returnValue
. - To send an asynchronous message back to the sender, you can use
event.reply(...)
event.sender.send(...)
will always send to the main frame.
PS: 如果能耐心的看完這段話,我就不會被坑了小1天的時間,教訓呀