简体   繁体   中英

How would I parse requested cookies using puppeteer and save them to a variable to be called later?

im trying to parse specific valus from these cookies and save them to a variable to be used later but I cant seem to figure it out. Im using puppeteer to login and then request the cookies after logging in.

Im using puppeteers cookie request like this.

const returnedCookies = await page.cookies()
console.log(returnedCookies); 

Which outputs this and a few other strings. But I wanted to know how to get the value of that "mystate" and store it into a variable.

{
    name: 'mystate',
    value: '1614736342244',
    domain: '.target.com',
    path: '/',
    expires: -1,
    size: 20,
    httpOnly: false,
    secure: false,
    session: true,
    sameParty: false
  },

Any input at all would be appreciated. Thank you:)

In your case returnedCookies is an array of objects. You can use find method for arrays to search through an array for one result:

const returnedCookies = await page.cookies();
const cookieNeeded = returnedCookies.find((cookie) => cookie.name ==='mystate');

let value = null;

// If the desired cookie is found in the array, get its value
if(typeof cookieNeeded !== 'undefined') {
  value = cookieNeeded.value;
}

// If the needed cookie wasn't found `value` will be null
console.log(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM