Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron webContents.send does not always work

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?

like image 378
EserRose Avatar asked Nov 21 '25 19:11

EserRose


1 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.

like image 106
Joshua Avatar answered Nov 24 '25 10:11

Joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!