简体   繁体   中英

ipcRenderer data not sent to ipcMain in Electron

I recently started developing desktop application using electron.

I want to send form details to main.js from the index.html on button click event. I have added a listener to the button in index.js. Searched online and found that I have to use ipcMain in main.js and ipcRenderer in index.js but the data is not being sent to ipcMain.

How do I get the form data in main.js?

In index.html

<div class="btn-div fld">
         <button id="loginButton" class="btn btn-primary st-btn" type="submit" name="button">Login</button>
</div> 
<script src="index.js" charset="utf-8"></script>

In index.js

document.querySelector("#loginButton").addEventListener('click', function(){
  userDetails = document.getElementById('login');
  username = userDetails.username.value;
  password = userDetails.password.value;
  console.log("Hello");
  const {ipcRenderer} = require('electron');
  ipcRenderer.send('asynchronous-message', username);
})

In main.js

const { app, BrowserWindow , ipcMain } = require('electron')

ipcMain.on('asynchronous-message', (event, arg) => {
  console.log( arg );
});

While creating a browser window in electron using new BrowserWindow(options) where options is an object. Define the object as:

options = {
    webPreferences: {
         preload: preload.js, //You need to create a file named preload.js (or any name) in your code
         nodeIntegration: true,
         contextIsolation: false,
    }
}

Now in a new file called preload.js :

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

In your snippet you added const { app }... which should be done this way to inject the javascript using a preload property in the object.

Now in the main app.js file (whatever you named maybe index.js ) where you created the browser window:

const ipc = require('electron').ipcMain; //Add to your pre-existing code
ipc.on("close-app", (event, message) => { //"close-app" can be anything but, you need to use the same key in the send message side (later in this answer)
    browserWindow.close(); //If you named the browserwindow as browserWindow
});

Now in your HTML (ie, send message side)

...
<script>
    window.ipcRenderer("close-app", ""); //Second parameter is used if you want to send some extra message. The extra message can be viewed in the server side from the message parameter in the app.js code (just above this paragraph)
</script>

This is a bit difficult if you are doing it for the first time. I've added more articles which will help you clear your confusions:
A related answer at StackOverflow
Relation with socket.io communication in NodeJS

While I have seen that the other answer to this question may have worked for others, it did not work for me... I was using webpack and, for the life of me, could not get it to work even when adding ExternalsPlugin commonjs and electron. The following worked instead:

main.js

ipcMain.on("download", (event, info) => {
info.properties.onProgress = status => win.webContents.send("downloadProgress", status);
  });

preload.js

contextBridge.exposeInMainWorld('electron', {
  api: {
    //receiving message from main.js
    responseProgress: (channel, func) => {
        let validChannels = ["downloadProgress"];
        if (validChannels.includes(channel)) { 
            ipcRenderer.on(channel, (event, ...args) => func(...args));
        }
    },
    process: (channel) => {
    //example for process that is called by button in reactjs etc
    }
});

ReactComponent.js

  function ReactComponent() {
  useEffect(() => {
        //retrieving information from preload.js originally sent from main.js
        window.electron.api.responseProgress("downloadProgress", (progress) => {
        console.log(progress);
        console.log(progress.percent);
        });
          }, []);
  return (
    //example of calling api on button click
    <button onClick={() => {
      window.electron.api.process("toMain");
    }}>Download</button>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM