3

I want to store my session cookie and authenticate my account using puppeteer.

Right now I'm using my username and password directly to authenticate.

const puppeteer = require('puppeteer');
(async ()=>{
  const browser= await puppeteer.launch({
     "headless": false,
     "slowMo":20    
  });
  const page= await browser.newPage();
  await page.goto("https://www.linkedin.com/login");
  await page.type('[id=username]','username');
  await page.type('[id=password]','password');
  await page.keyboard.press('Enter',{delay:2000});
  await browser.close();
})();
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
Rahul Baby
  • 159
  • 2
  • 2
  • 7

1 Answers1

4

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

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75