I am trying to:
The implementation I have attempted is as follows:
import puppeteer from 'puppeteer';
const createSession = async (browser, startUrl) => {
const page = await browser.newPage();
await page.goto(startUrl);
await page.waitForSelector('#submit');
const cookies = await page.cookies();
const url = await page.url();
return {
cookies,
url
};
};
const useSession = async (browser, session) => {
const page = await browser.newPage();
for (const cookie of session.cookies) {
await page.setCookie(cookie);
}
await page.goto(session.url);
};
const run = async () => {
const browser = await puppeteer.launch({
headless: false
});
const session = await createSession(browser, 'http://foo.com/');
// The session has been established
await useSession(browser, session);
await useSession(browser, session);
};
run();
createSession
is used to capture the cookies of the loaded page.useSession
are expected to load the page using the existing cookies.However, this does not work – the session.url
page does not recognise the session. It appears that not all cookies are being captured this way.
It appears that page#cookies
returns some cookies with the session=true,expires=0
configuration. setCookie
ignores these values.
I worked around this by constructing a new cookies array overriding the expires
and session
properties.
const cookies = await page.cookies();
const sessionFreeCookies = cookies.map((cookie) => {
return {
...cookie,
expires: Date.now() / 1000 + 10 * 60,
session: false
};
});
At the time writing this answer, session
property is not documented. Refer to the following issue https://github.com/GoogleChrome/puppeteer/issues/980.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With