Here below is an example of how to login on a web app using Puppeteer. You need to install apify (a npm module).
const Apify = require('apify');
Apify.main(async () => {
const input = await Apify.getValue('INPUT');
const browser = await Apify.launchPuppeteer();
const page = await browser.newPage();
await page.goto('https://facebook.com');
// Login
await page.type('#email', input.username);
await page.type('#pass', input.password);
await page.click('#loginbutton input');
await page.waitForNavigation();
// Get cookies
const cookies = await page.cookies();
// Use cookies in other tab or browser
const page2 = await browser.newPage();
await page2.setCookie(...cookies);
await page2.goto('https://facebook.com'); // Opens page as logged user
await browser.close();
console.log('Done.');
});
To Save the Session Cookies in puppeteer.
const cookiesObject = await page.cookies()
// Write cookies to temp file to be used in other profile pages
jsonfile.writeFile(cookiesFilePath, cookiesObject, { spaces: 2 },
function(err) {
if (err) {
console.log('The file could not be written.', err)
}
console.log('Session has been successfully saved')
})
Then, on your next iteration right before using page.goto()
you can call page.setCookie()
to load the cookies from the file one by one.
const previousSession = fileExistSync(cookiesFilePath)
if (previousSession) {
// If file exist load the cookies
const cookiesArr = require(`.${cookiesFilePath}`)
if (cookiesArr.length !== 0) {
for (let cookie of cookiesArr) {
await page.setCookie(cookie)
}
console.log('Session has been loaded in the browser!')
return true
}
}
The CDPSession instances are used to talk raw Chrome Devtools Protocol:
- Protocol methods can be called with
session.send
method.
- Protocol events can be subscribed to with
session.on
method.
Here are the official links for these as follows:
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagecookiesurls
https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagesetcookiecookies