shee
shee

Reputation: 145

mainWindow.webContents.send does not work

I am trying to send response from python axios.post to ipcRenderer but mainWindow.webContents does not send the response to renderer and sometime the response from axios is delayed please help me with this

main.js

axios.post(`${pythonHost}/send-request/`,options)
.then(function(response){
mainWindow.webContents.on('did-finish-load', function () {
mainWindow.webContents.send('request_status:success',JSON.stringify(response.data))
});
});

index.js

ipcRenderer.on('request_status:success',(e,response)=>{
\\
})

Upvotes: 0

Views: 536

Answers (1)

aabuhijleh
aabuhijleh

Reputation: 2464

In your code, mainWindow.webContents.send will never run unless did-finish-load is fired. This event will only fire when the page has loaded and it won't fire again

So in your case, you are just waiting forever for an event that won't get fired and you are never executing mainWindow.webContents.send

axios.post(`${pythonHost}/send-request/`, options).then(function (response) {
  mainWindow.webContents.on("did-finish-load", function () {
    // this will not run until the "did-finish-load" fires !
    mainWindow.webContents.send(
      "request_status:success",
      JSON.stringify(response.data)
    );
  });
});

You probably want to do something like this instead

const { once } = require("events");

let didFinishLoad = false;

mainWindow.webContents.on("did-finish-load", function () {
  didFinishLoad = true;
});

axios
  .post(`${pythonHost}/send-request/`, options)
  .then(async function (response) {
    if (!didFinishLoad) {
      // wait until did-finish-load is fired
      await once(mainWindow.webContents, "did-finish-load");
    }

    mainWindow.webContents.send(
      "request_status:success",
      JSON.stringify(response.data)
    );
  });

Upvotes: 2

Related Questions