Home Properly getting Electron cookies (asynchronous)
Reply: 1

Properly getting Electron cookies (asynchronous)

Grim Reaper
1#
Grim Reaper Published in 2017-12-06 16:58:10Z

I think I have a good understanding of what asynchronous means in JavaScript.
I am well aware that I can use something like callback functions to modify variables from asynchronous functions.

I am not, however, sure how to use this with the cookies in Electron.
What I mean is, I can get the cookie by doing:

function getCookie( name ) {

    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
    });

}

I can easily output the cookie to the console. However, since this is asynchronous, I don't know how to set any variables.

  • How can I achieve this? How do I set a variable form inside the 'cookies.get' method, since I can not use callbacks?
Matt Spinks
2#
Matt Spinks Reply to 2017-12-06 17:02:06Z

You might try the use of a global variable:

var cookieLoaded = false;
function getCookie( name ) {
    // 'ses' refers to 'mainWindow.webContents.session'
    ses.cookies.get({name: name}, function(err, cookie) {
        if ( err ) throw err;
        console.log(cookie[0].value);
        cookieLoaded = true;
    });
}

//in other parts of the code...
//you probably want this to be in events, like click handlers, etc.

if (cookieLoaded) {
  //DO STUFF
} else {
  alert('You are not authenticated');
  //or, disable buttons, etc.
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320157 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO