Use Google Sign In cookies to open an already signed in page (puppeteer)

Viewed 440

What I want is to get a cookie and re-use it whenever I want to open an already signed in puppeteer instance. I tried this, but it didn't work:

Function which would get cookies:

async function writeCookies(page, cookiesPath) {
    const client = await page.target().createCDPSession();
    // This gets all cookies from all URLs, not just the current URL
    const cookies = (await client.send("Network.getAllCookies"))["cookies"];
    console.log(cookies)
    console.log("Saving", cookies.length, "cookies");
    // fs.writeFileSync(cookiesPath, JSON.stringify(cookies));
    console.log(cookiesPath)
    console.log(cookies)
    // await fs.writeJSON(cookiesPath, cookies);
  }

How I implemented it:

const page = await browser.newPage();
time = new Date()
await page.goto("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession")
await page.$eval('#identifierId', (el) => (el.value = "test@gmail.com"));
await page.click("#identifierNext > div > button > div.VfPpkd-RLmnJb");
await page.waitForSelector('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', { visible: true });
await page.$eval('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', (el) => (el.value = "Tester"));
await page.waitForSelector('#passwordNext > div > button > div.VfPpkd-RLmnJb', { visible: true });
await sleep(1000)
await page.click("#passwordNext > div > button > div.VfPpkd-RLmnJb");
writeCookies(page,"./WebHook.js")

How I would send the cookies:

await page.setExtraHTTPHeaders({cookies :`${cookies}`})

I also tried this way:

async function restoreCookies(page, cookiesPath) {
  try {
    // const cookies = await fs.readJSON(cookiesPath);
    let buf = fs.readFileSync(cookiesPath);
    let cookies = JSON.parse(buf);
    console.log("Loading", cookies.length, "cookies into browser");
    await page.setCookie(...cookies);
  } catch (err) {
    console.log("restore cookie error", err);
  }
}

Maybe I am retrieving the wrong cookies.

0 Answers
Related