node.jsplaywright

How to add custom headers in Playwright


headers["user-agent"] = fakeUa();
  console.log(fakeUa())
  let firstReq = true;
    page.route('**/*', route => {
    const request = route.request()
    //console.log(request.url(), JSON.stringify(request.headers()));
    
    if("x-j3popqvx-a" in request.headers()){
        headers = request.headers();
        //console.log(headers);
        console.log("exiting");
        return;
    }
    else {
        console.log("in");
        return route.continue({headers: headers});
    }
  });
  let pageRes = await page.goto(url, {waitUntil: 'load', timeout: 0});

I want to add fake user agent when sending request to url. But it doesn't add the fake useragent rather goes with the default one.


Solution

  • While in puppeteer it was possible with the page.setUserAgent() method to apply a custom UA and page.setExtraHTTPHeaders() to set any custom headers, in playwright you can set custom user agent (userAgent) and headers (extraHTTPHeaders) as options of browser.newPage() or browser.newContext() like:

    const page = await browser.newPage({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36' })
    
    const page = await browser.newPage({ 
      extraHTTPHeaders: { 
        'Cache-Control': 'no-cache' 
      } 
    })
    

    Edit: In case you are using it with newContext() usage looks like this (make sure to set userAgent in the settings of newContext and not in newPage!):

    const context = await browser.newContext({ userAgent: 'hello' })
    const page = await context.newPage()
    // to check the UA:
    console.log(await page.evaluate(() => navigator.userAgent))