Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session.cookies is empty while JavaScript document.cookie is not

I want to get all the cookies from a BrowserWindow object, including HTTPonly cookies. I've read through the documentation that the following code will output all the cookies being used in the BrowserWindow: windowObject.webContents.session.cookies. This returns an empty cookies object: Cookies: {}.

If I use the following code, I do get all the cookies except for the much needed HTTPonly (which are not returned due to security purposes):

return windowObject.webContents.executeJavaScript(`document.cookie;`,true).then(function(result){
 console.log(result);
});

Proof of the issue; Place this code inside your app.on('ready') function:

const Window = electron.BrowserWindow;
var windowObject = new Window({show: true, webPreferences:{images:false}});
windowObject.loadURL("https://www.tweakers.net");
windowObject.webContents.on('did-finish-load', function() {
  console.log(windowObject.webContents.session);
  console.log(windowObject.webContents.session.cookies);
  windowObject.webContents.executeJavaScript(`document.cookie;`, true).then(function(result){
    console.log(result);
  });
});

Returns (this is truncated by me):

Truncated result from the commandline Why is it that the session returns no cookies? How can this be fixed?

I'm using Electron: 1.7.5

Thanks for your help in advance!

like image 411
Dragon54 Avatar asked Aug 18 '26 13:08

Dragon54


1 Answers

windowObject.webContents.session.cookies returns the defaultSession session object. Which put me on the wrong track of believing there was an unique session object tied to the windowObject object.

The cookies in my case could be retrieved through the following code:

const electron = require('electron');
const Window = electron.BrowserWindow;
var windowObject = new Window({show: true, webPreferences:{images:false}});
windowObject.loadURL("https://www.tweakers.net");
windowObject.webContents.on('did-finish-load', function() {
  windowObject.webContents.session.cookies.get({}, (error, cookies) => {
    console.log(cookies);
  });
});

It is also possible to get all the cookies through the following code:

const electron = require('electron');
const session = electron.session;

return session.defaultSession.cookies.get({}, (error, cookies) => {
  console.log(cookies);
});

It is possible to filter on these to get the correct cookies belonging to a domain name for instance. To do this just simply use:

anySessionObject.cookies.get({domain: "yourdomain.com"}, (error, cookies) => {
  console.log(cookies);
});

A ticket about my findings has been opened on GitHub. You can view it here: https://github.com/electron/electron/issues/10364

like image 118
Dragon54 Avatar answered Aug 21 '26 05:08

Dragon54