Playwright Screenshots: Custom Headers for Many URLs
In this article
This guide shows you how to use Playwright to capture screenshots of multiple URLs while sending custom HTTP headers with each request. This is useful for testing pages behind authentication, previewing personalized content, or capturing pages that require specific headers to render correctly. You'll end up with a reusable script that loops through a list of URLs, applies your headers, and saves a screenshot for each one.
What You'll Need
- Node.js installed on your machine (version 16 or later recommended)
- A code editor (like VS Code)
- Basic familiarity with the command line/terminal
- Your list of URLs and the custom headers you want to send
Step-by-Step
- Set up a new Node.js project
Create a new folder for your project and open it in your terminal. Run
npm init -yto create apackage.jsonfile with default settings. - Install Playwright
Run
npm install playwrightto install the Playwright library. Then, install the browser you plan to use (e.g., Chromium) withnpx playwright install chromium. You can also use Firefox or WebKit if you prefer. - Create your script file
Create a new file, e.g.,
screenshots.js, in your project folder. This will contain all the logic. - Import Playwright and define your URLs and headers
At the top of your script, require Playwright and define an array of URLs and an object containing your custom headers. For example:
const { chromium } = require('playwright'); const urls = [ 'https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3' ]; const customHeaders = { 'Authorization': 'Bearer your-token-here', 'X-Custom-Header': 'custom-value' }; - Create an async function to take screenshots
Define an async function that will launch the browser, create a new context with the headers, and loop through the URLs. Here's the structure:
async function takeScreenshots() { const browser = await chromium.launch(); const context = await browser.newContext(); // Add headers to the context await context.setExtraHTTPHeaders(customHeaders); for (const url of urls) { const page = await context.newPage(); try { await page.goto(url, { waitUntil: 'networkidle' }); const filename = url.replace(/[^a-z0-9]/gi, '_') + '.png'; await page.screenshot({ path: filename, fullPage: true }); console.log('Saved screenshot for ' + url); } catch (error) { console.error('Failed for ' + url + ': ' + error.message); } finally { await page.close(); } } await browser.close(); } takeScreenshots(); - Run the script
Execute the script with
node screenshots.js. You should see console logs for each successful screenshot, and the PNG files will appear in your project folder. - Customize the screenshot options
You can adjust the screenshot behavior by modifying the
page.screenshot()call. For example, setfullPage: falseto capture only the visible viewport, or addtype: 'jpeg'with a quality setting if you prefer JPEG files. - Handle dynamic content (optional)
If your pages load content asynchronously, you might need to wait for specific elements before taking the screenshot. Use
await page.waitForSelector('selector')afterpage.goto()to ensure the content is rendered.
Common Mistakes
- Forgetting to set headers before navigation – The headers must be set on the context before calling
page.goto(). If you set them after, they won't apply to the initial request. - Using
waitUntil: 'networkidle'on pages with continuous network activity – Some pages (e.g., with live updates) never reach 'networkidle', causing the script to hang. Use'load'or'domcontentloaded'instead. - Not closing pages or the browser – If you don't close the browser, the script will hang. Always use
await browser.close()in afinallyblock or after the loop. - Screenshot filename collisions – If two URLs produce the same sanitized filename, the later screenshot will overwrite the earlier one. Add an index or hash to the filename to avoid this.
Tips
- Use a separate context per URL if headers need to vary – If different URLs need different headers, create a new context for each URL instead of reusing one context.
- Set a viewport size – Use
browser.newContext({ viewport: { width: 1280, height: 720 } })to control the screenshot dimensions. - Add a delay between screenshots – If you're hitting a server that rate-limits, add
await page.waitForTimeout(1000)between requests. - Log errors with the URL – This makes it easier to identify which URL failed and why.
- Store screenshots in a subfolder – Create a
screenshotsdirectory and usepath.join('screenshots', filename)to keep things organized.
Troubleshooting
- Screenshots are blank or missing content – This often happens because the page hasn't finished loading. Try increasing the wait time or using
waitUntil: 'networkidle'if appropriate. Also check if the custom headers are actually required for the content to render. - Headers are not being sent – Verify that you're calling
context.setExtraHTTPHeaders()before any navigation. Also, check that the header names are correct (case-sensitive for some servers). You can verify by loggingpage.request.headersin a script. - Script hangs on a particular URL – This is usually due to
waitUntil: 'networkidle'on a page with continuous requests. Switch to'load'or add a timeout:page.goto(url, { timeout: 30000 }). - Browser not found – If you get an error like "Executable doesn't exist", run
npx playwright installto download the browser binaries. - Permission errors when saving screenshots – Make sure the output directory exists and is writable. Use
fs.mkdirSync('screenshots', { recursive: true })before the loop.
Frequently Asked Questions
Can I use this with Firefox or WebKit?
Yes. Replace chromium with firefox or webkit in the launch line and install the corresponding browser with npx playwright install firefox (or webkit).
How do I send different headers for different URLs?
Instead of setting headers on the shared context, create a new context for each URL and set headers on that context before navigating. For example, inside the loop, call const context = await browser.newContext(); await context.setExtraHTTPHeaders(headersForThisUrl);.
Can I capture screenshots in a specific format like JPEG or WebP?
Yes. In the page.screenshot() call, add type: 'jpeg' or type: 'webp'. For JPEG, you can also specify quality: 80 to control compression.
How do I wait for a specific element before taking the screenshot?
After page.goto(), use await page.waitForSelector('#content') where #content is the selector for the element you need. This ensures the element is present and visible.
Is it possible to take screenshots of pages that require login?
Yes. You can either send the session cookie as a custom header (if the site accepts it) or use Playwright's storage state: log in once, save the storage state, and then use it in your script with browser.newContext({ storageState: 'state.json' }).
Can I run this script in parallel to speed things up?
Yes. You can use Promise.all to process multiple URLs concurrently, but be mindful of server load and rate limits. A simple way is to split the URLs into chunks and process each chunk with a separate browser context.