Rayrun

How do I log the headers of a request using Playwright?

Answer

To log the headers of a request using @playwright/test, you can use the request.headers() method from the Playwright API's Request class. This method returns an object containing all the HTTP headers associated with the request.

Here's a TypeScript example of how to log request headers using Playwright:

import { test, expect } from '@playwright/test';

test('log request headers', async ({ page }) => {
  // Add an event listener for 'request' events
  page.on('request', (request) => {
    // Get the headers object
    const headers = request.headers();

    // Log the headers
    console.log('Request headers:', headers);
  });

  // Navigate to the website
  await page.goto('https://ray.run/');
});

If you want to log a specific header value, use the request.headerValue(name) method. This method returns a Promise that resolves to either null (if no matching header was found) or a string containing the value of the matching header.

Here's an example of logging a specific header value:

import { test, expect } from '@playwright/test';

test('log specific request header', async ({ page }) => {
  // Add an event listener for 'request' events
  page.on('request', async (request) => {
    // Get the value of a specific header
    const headerValue = await request.headerValue('user-agent');

    // Log the header value
    console.log('User-Agent header value:', headerValue);
  });

  // Navigate to the website
  await page.goto('https://ray.run/');
});

These examples demonstrate how to log request headers using Playwright's Request class and the request.headers() and request.headerValue(name) methods.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.