Electron webContents.send does not always work

Viewed 752

I use the following to send some data to another window;

try{ 
    win.webContents.once('dom-ready', () => win.webContents.send('send-data', data)); 
}
catch(err){
    console.log("Caught ",err);
}   

And for receivig;

ipcRenderer.on('send-data', function (event,data) {     
    console.log("Loaded ", data);   
 });

The thing is, the "data" here is sometimes assembled very quickly and it works fine. However, sometimes it takes a while and the other window is already loaded at this point. No data is received in that case, and no error message either. But then I can simply use the following to send it without problems;

win.webContents.send('send-data', data)

I couldn't find a way to apply for both cases. Any suggestions?

2 Answers

The short answer is no.

Electron doesn't have a function to wait for the window to load, then send a message, or send a message right away if the window's already loaded.

However this can be done with some simple code:

var hasWindowLoaded = false;
var hasDataBeenSent = false;
var data            = {};

win.webContents.once('dom-ready', () => {
    hasWindowLoaded = true;
    if (!hasDataBeenSent && data) {
        win.webContents.send('send-data', data);
        hasDataBeenSent = true;
    }
});

// Now add this where you build the `data` variable.
function loadData () {
    data = {'sampleData': 'xyz'};

    if (!hasDataBeenSent && hasWindowLoaded) {
        win.webContents.send('send-data', data);
        hasDataBeenSent = true;
    }
}

Once the data's loaded in loadData it'll check if the window's finished loading and if it has then it sends the data right away.

Otherwise it stores the data in a varible (data) and once the window loads it sends it to the window.

Another approach that you may want to consider is sending data to the browserWindow using query strings.

const data = { hello: "world" }; // sample data

// send it using query strings
browserWindow.loadFile(YOUR_HTML_FILE_PATH, {
  query: { data: JSON.stringify(data) },
});


// parse this data in the browserWindow
const querystring = require("querystring");
const query = querystring.parse(global.location.search);
const data = JSON.parse(query["?data"]);
console.log(data); // { hello: "world" }
Related