I am currently having the problem (puppeteer) in a project that I think cookies are not activated. But I also don't know how to activate them if they are not already activated from the beginning.
I am currently having the problem (puppeteer) in a project that I think cookies are not activated. But I also don't know how to activate them if they are not already activated from the beginning.
Share Improve this question asked Oct 8, 2021 at 13:07 Lauritz TiesteLauritz Tieste 591 gold badge1 silver badge7 bronze badges 2-
1
can you clarify a bit how you mean this? what is your initial set up in puppeteer? what is the behavior that suggests "cookies are not activated"? you can use
page.cookies()
to get all the cookies on the current page so you can check for yourself if they are set or not. – theDavidBarton Commented Oct 8, 2021 at 14:15 - Hi and wele to StackOverflow. Please refer to stackoverflow./help/how-to-ask on how to ask a proper question and improve yours according the guidelines. As a first step, please add the code you already tried as a stackoverflow./help/mcve and describe how it doesnt work for you. – Fabian S. Commented Oct 12, 2021 at 6:35
1 Answer
Reset to default 2Since every website nowaday has Captcha, so we can skip the auto-login part. I'm new too, I got an idea from here for this.
Firstly check if there is saved cookies.json file, if not, do the manually login, you click the submit button yourself and solve the captcha puzzle (in non-headless mode), the page should be redirected to destination page.
Once the destination page is loaded, save the cookies in to a Json file for next time.
Example:
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
const browser = await puppeteer.launch({
headless: false, //launch in non-headless mode so you can see graphics
defaultViewport: null
});
let [page] = await browser.pages();
await page.setRequestInterception(true);
const getCookies = async (page) => {
// Get page cookies
const cookies = await page.cookies()
// Save cookies to file
fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 4), (err) => {
if (err) console.log(err);
return
});
}
const setCookies = async (page) => {
// Get cookies from file as a string
let cookiesString = fs.readFileSync('./cookies.json', 'utf8');
// Parse string
let cookies = JSON.parse(cookiesString)
// Set page cookies
await page.setCookie.apply(page, cookies);
return
}
page.on('request', async (req) => {
// If URL is already loaded in to system
if (req.url() === 'https://example./LoggedUserCP') {
console.log('logged in, get the cookies');
await getCookies(page);
// if it's being in login page, try to set existed cookie
} else if (req.url() === 'https://example./Login?next=LoggedUserCP') {
await setCookies(page);
console.log('set the saved cookies');
}
// otherwise go to login page and login yourself
req.continue();
});
await page.goto('https://example./Login?next=LoggedUserCP');
})();