jamesfdearborn
jamesfdearborn

Reputation: 799

Puppeteer Set Request Cookie Header

I'm trying to set the cookies on each request via Puppeteer request interception. I've noticed that while setting headers['sample-header']=1 creates header 'sample-header' equal to 1, setting headers['cookie'] = x... does not set the requests cookie. For instance, the following code does not set any requests cookies.

const browser = await puppeteer.launch({headless: false,executablePath:dirnae});
const page = await browser.newPage();
const client = await page.target().createCDPSession();

await page.setRequestInterception(true);

page.on('request', request => {
    const headers = request.headers();
    headers['cookie'] = 1;
    request.continue({ headers });
});

page.on('request', request => {
    console.log(request.headers())
});

page.on('response', response => {
    //console.log(response.headers()['set-cookie'])
});

await page.goto('https://google.com');

EDIT: I figured out that I can see the requests cookie header thru handling of the Network.requestWillBeSentExtraInfo event.

However, I can't seem to edit requests in that event.

Upvotes: 2

Views: 8015

Answers (1)

dee.ronin
dee.ronin

Reputation: 1038

You cannot change the cookie per network request. You can use the page.setCookie and provide a cookie for different url or domain. Below is the code for reference:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    var cookies = [
        {
            "name": "sample-cookie1",
            "value": "1",
            "domain": "stackoverflow.com"
        },
        {
            "name": "sample-cookie2",
            "value": "2",
            "domain": "pptr.dev"
        }
    ];

    await page.setCookie(...cookies);

    await page.goto("https://pptr.dev");

    console.log(await page.cookies()); //this will have the **sample-cookie2** cookie

    await page.goto("https://stackoverflow.com");

    console.log(await page.cookies()); //this will have the **sample-cookie1** cookie

})();

Upvotes: 1

Related Questions