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


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

renderer.js文件

const ele_sendbtn = document.getElementById("send_btn")
ele_sendbtn.onclick = function () {
 console.log("this is renderer output log" ,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) {

    let data = 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 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(...). This helper method will automatically handle messages coming from frames that aren't the main frame (e.g. iframes) whereas event.sender.send(...) will always send to the main frame.

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM