There are two possible scenarios:
1- Remote URL
if you are trying to load a remote URl i.e
new BrowserWindow().loadURL('www.example.com')
than you can set/get cookies by modifying default session and these cookies will be used in all requests to that URL
const { session } = require('electron')
// Query all cookies.
session.defaultSession.cookies.get({})
.then((cookies) => {
console.log(cookies)
}).catch((error) => {
console.log(error)
})
// Query all cookies associated with a specific url.
session.defaultSession.cookies.get({ url: 'http://www.github.com' })
.then((cookies) => {
console.log(cookies)
}).catch((error) => {
console.log(error)
})
// Set a cookie with the given cookie data;
// may overwrite equivalent cookies if they exist.
const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }
session.defaultSession.cookies.set(cookie)
.then(() => {
// success
}, (error) => {
console.error(error)
})
refrence : electron cookies api
2-Local URL
if you are trying to load a local URl i.e
new BrowserWindow().loadURL(`file://${__dirname}/index.html`)
OR
new BrowserWindow().loadFile('index.html')
and you are using fetch API or XMLHTTPrequest in your local HTML file(index.html) to send GET/POST request to a webserver and trying to set or retrieve cookies, I have bad news for you, I searched for four to five hours and didnt found any simple method that allows you to set or retrieve cookies using fetch or XMLHTTPRequest. Only solution I went for is to enable node integration in BrowserWindow and use nodes https and http modules. My code:
app.js/index.js (entry point)
const { app, BrowserWindow } = require('electron');
app.on('ready', () => {
let mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
mainWindow.loadURL(`file://${__dirname}/main.html`);
});
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Data Set</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="d-flex vw-100 vh-100 justify-content-center align-items-center">
<form id="jform" class="text-center">
<input type="text" class=" mt-3 form-control" id="jcaptcha" placeholder="Type captcha here">
<button type="submit" id="sbmt" class="btn w-100 btn-primary mt-2 d-block">Submit</button>
</form>
</div>
<script src="helper.js"></script>
<script src="main.js"></script>
</body>
</html>
helper.js
const https = require('https');
// proxy setup to debug requests using Fiddler
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
// const proxy = require("node-global-proxy").default;
// proxy.setConfig({
// http: "http://127.0.0.1:8888",
// https: "http://127.0.0.1:8888",
// });
// proxy.start();
function sendHttpsGetRequest(targetUrl, cookies, callback) {
const requestOptions = {
method: 'GET',
headers: {
'Cookie': cookies.join('; ')
},
};
const getRequest = https.get(targetUrl, requestOptions, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
callback(null, data, response.headers);
});
});
getRequest.on('error', (error) => {
callback(error, null);
});
getRequest.end();
}
function sendHttpsPostRequest(targetUrl, cookies, postData, callback) {
const postRequestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
'Cookie': cookies.join('; '),
},
};
const postRequest = https.request(targetUrl, postRequestOptions, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
callback(null, data, response.headers);
});
});
postRequest.on('error', (error) => {
callback(error, null, null);
});
postRequest.write(postData);
postRequest.end();
}
// Usage :
const targetUrl = 'https://example.com';
const cookies = ['cookie1=abc', 'cookie2=def'];
const postData = 'key1=value1&key2=value2';
sendHttpsGetRequest(targetUrl, cookies, (error, data, headers) => {
if (error) {
console.log('GET Request Error:', error);
} else {
var redirect = headers['location']
var cookie = headers['set-cookie']
var response_text = data
}
});
sendHttpsPostRequest(targetUrl, cookies, postData, (error, data, headers)=>{
if (error) {
console.log('POST Request Error:', error);
} else {
var redirect = headers['location']
var cookie = headers['set-cookie']
var response_text = data
}
})