cookieselectron

Persistant cookies in Electron 5


I'm loading a web page URL in Electron except when the app is closed the cookies are empty after opening again. I can't update because plugin support was removed, so I'm stuck at 5.x version. I've tried a few different things with no luck. What is the best way to get persistent cookies in Electron 5?

The following is a wrokaround I tried. However, it didn't work.

const {electron, app, BrowserWindow} = require('electron');
const path = require('path')
const fs = require('fs');
const dataPath = app.getPath('userData')
const filePath = path.join(dataPath, 'config');

  mainWindow = new BrowserWindow({
    webPreferences: {
      plugins: true,
      nodeIntegration: false
    }
  });

  try {
    console.log(fs.readFileSync(filePath, 'utf8'))
    mainWindow.webContents.executeJavaScript(
      "document.cookie = '" + fs.readFileSync(filePath, 'utf8') + "';"
    )
  } catch (e) {
    console.log(e)
  }

  mainWindow.loadURL('https://www.example.com/')

  mainWindow.on('close', function () {
    mainWindow.webContents
    .executeJavaScript('document.cookie;')
    .then(cookies => {
      console.log(cookies)
      fs.writeFileSync(filePath, cookies)
    })
  })

Solution

  • Here's what worked for me.

      mainWindow = new BrowserWindow({
        webPreferences: {
          partition: 'persist:MyAppSomethingUnique'
        }
      });
    
      mainWindow.on('did-start-navigation', function() {
        session.defaultSession.cookies.flushStore();
      });
    
      mainWindow.on('did-navigate', function() {
        session.defaultSession.cookies.flushStore();
      });