YouTip LogoYouTip

Playwright Javascript

Playwright JavaScript Execution | Online Tutorial

Playwright JavaScript Execution | Online Tutorial

This chapter introduces how to execute JavaScript code in Playwright, including page context execution, parameter passing, and initialization script injection.


page.evaluate() Page Context Execution

page.evaluate() executes code in the page's JavaScript environment and can access DOM and page global variables.

Example

test('Get page data', async ({ page }) => {

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

 // Get page title (executed in page context)

 const title = await page.evaluate(() => {

  return document.title;

 });

 console.log('Page title:', title);

 // Get the number of all links on the page

 const linkCount = await page.evaluate(() => {

  return document.querySelectorAll('a').length;

 });

 console.log('Link count:', linkCount);

 // Get page scroll position

 const scrollY = await page.evaluate(() => {

  return window.scrollY;

 });

});

Passing Parameters to evaluate

The second parameter of page.evaluate() will be passed to the function inside the page.

Example

test('Pass parameters to page', async ({ page }) => {

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

 // Pass single parameter

 const result1 = await page.evaluate((name) => {

  return `Hello, ${name}!`;

 }, 'TUTORIAL');

 // Pass object parameter

 const userInfo = { name: 'tutorial', role: 'admin' };

 const result2 = await page.evaluate((user) => {

  return `${user.name}'s role is ${user.role}`;

 }, userInfo);

 // Pass multiple parameters (using destructuring)

 const result3 = await page.evaluate(

  ({ x, y }) => {

   return x + y;

  },

  { x: 10, y: 20 }

 );

 console.log('10 + 20 =', result3); // 30

});

The passed parameters will be serialized to JSON and sent to the page context, so functions, DOM elements, and other non-serializable objects cannot be passed.

The returned values will also be serialized.


locator.evaluate() Element Context Execution

locator.evaluate() executes code in the matched element's context, and the parameter includes the DOM node reference of that element.

Example

test('Get element DOM property', async ({ page }) => {

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

 // Get textContent of a specific element

 const text = await page

  .getByRole('heading', { name: 'TUTORIAL' })

  .evaluate(node => node.textContent);

 // Get element's style property

 const color = await page

  .getByRole('button', { name: 'Search' })

  .evaluate(node => getComputedStyle(node).backgroundColor);

});

locator.evaluateAll() Iterate All Matched Elements

evaluateAll() executes the same code on all matched elements and returns an array.

Example

test('Get text of all list items', async ({ page }) => {

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

 // Get text of all menu items

 const menuItems = await page

  .getByRole('navigation')

  .locator('a')

  .evaluateAll(links => links.map(link => link.textContent));

 console.log('Menu items:', menuItems);

 // ['Home', 'Tutorial', 'Tools', ...]

});

page.addInitScript() Inject Initial Script

addInitScript() injects JavaScript code before the page loads, allowing you to modify the browser environment before page script execution.

Example

test('Inject initial script', async ({ page }) => {

 // Modify navigator property before page loads

 await page.addInitScript(() => {

  // Override WebDriver detection

  Object.defineProperty(navigator, 'webdriver', {

   get: () => false,

  });

  // Mock global variable on window

  window.TUTORIAL_CONFIG = {

   env: 'test',

   version: '1.0.0',

  };

 });

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

 // Verify injected variable takes effect

 const config = await page.evaluate(() => window.TUTORIAL_CONFIG);

 console.log(config); // { env: 'test', version: '1.0.0' }

});

Common uses of addInitScript():

Usage Description
Mock browser API Override navigator.webdriver, navigator.language, etc.
Inject custom configuration Set test environment variables, mock data sources, etc.
Disable features Turn off Service
← Playwright PomPlaywright Visual β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.