Wednesday, 24 March 2021

how to use google sign in cookies to open an already signed in page (puppeteer)

so what i want is to get a cookie and re use it whenever i want to open an already signed in puppeteer instance i did this way but didnt worked

this is the 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 am using it and getting the cookies

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")

and sending the cookies in this way await page.setExtraHTTPHeaders({cookies :${cookies}})

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 am retrieving the wrong cookies.



from how to use google sign in cookies to open an already signed in page (puppeteer)

No comments:

Post a Comment