Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Playwright page.evaluate Patterns

БесплатноБез исполняемых скриптовНе проверен

Teaches the agent when and how to use page.evaluate, evaluateHandle, and exposeFunction in Playwright — passing arguments safely, reading DOM/JS state, and…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

Playwright page.evaluate Patterns

This skill makes the agent use page.evaluate the way it is meant to be used: to read application state from the browser, not to replace user actions. The function body runs inside the page's JS context, so document, window, and app globals are available — but Node closures and imports are not. Arguments must be explicitly serialized across the bridge.

Use this skill when the agent needs to inspect localStorage, read a JS variable, call a page API, or scrape computed values — and to stop the agent from clicking via evaluate(() => el.click()) when a locator would be correct.

Core Principles

  1. Read with evaluate, act with locators. Use evaluate to extract state. Use page.getByRole(...).click() for interactions — locators auto-wait and reflect real user behavior; el.click() inside evaluate bypasses actionability checks and hides bugs.
  2. The callback runs in the browser, not Node. No access to test variables, require, process.env, or imported helpers unless passed as an argument.
  3. Arguments must be serializable (JSON-compatible) — except JSHandle/ElementHandle, which are passed by reference. Functions, class instances, and undefined keys do not cross intact.
  4. evaluate returns serialized values; evaluateHandle returns a live handle. Use a handle when you need to keep referencing a non-serializable object (e.g. window, a DOM node) across calls.
  5. Treat all page input as untrusted. Never build the evaluated source by string-concatenating page content — pass data as an argument so it can never be interpreted as code.

Workflow / Patterns

Pattern 1 — Read JS / DOM state (the primary use)

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

test('reads application state from the page', async ({ page }) => {
  await page.goto('https://example.com/app');

  // Read a global the app sets.
  const userId = await page.evaluate(() => (window as any).__APP__?.currentUser?.id);
  expect(userId).toBeTruthy();

  // Read localStorage (impossible to assert on from Node directly).
  const theme = await page.evaluate(() => localStorage.getItem('theme'));
  expect(theme).toBe('dark');

  // Read a computed style the user actually sees.
  const color = await page.evaluate(() => {
    const btn = document.querySelector('button.primary')!;
    return getComputedStyle(btn).backgroundColor;
  });
  expect(color).toBe('rgb(37, 99, 235)');
});

Pattern 2 — Pass arguments safely (single arg, then object/array)

evaluate takes exactly one argument. Bundle multiple values into an object or array.

test('passes data into the page context', async ({ page }) => {
  await page.goto('https://example.com');

  // Single primitive.
  const doubled = await page.evaluate((n) => n * 2, 21);
  expect(doubled).toBe(42);

  // Multiple values -> wrap in an object, destructure inside.
  const fullName = await page.evaluate(
    ({ first, last }) => `${first} ${last}`.trim(),
    { first: 'Ada', last: 'Lovelace' },
  );
  expect(fullName).toBe('Ada Lovelace');

  // Seed app state for a test scenario.
  await page.evaluate((token) => {
    localStorage.setItem('auth_token', token);
  }, process.env.TEST_TOKEN ?? 'test-token-123');
});

Pattern 3 — Pass a located element into evaluate

A Locator resolves to an element handle that crosses the bridge by reference, so you can operate on the exact element the locator found.

test('evaluates against a located element', async ({ page }) => {
  await page.goto('https://example.com/products');

  const card = page.getByRole('article', { name: 'Pro Plan' });

  // The first arg of the callback is the resolved element node.
  const data = await card.evaluate((el) => ({
    price: el.querySelector('.price')?.textContent?.trim(),
    inStock: el.getAttribute('data-in-stock') === 'true',
    width: el.getBoundingClientRect().width,
  }));

  expect(data.inStock).toBe(true);
  expect(Number(data.width)).toBeGreaterThan(0);

  // Pass extra args alongside the element (element first, then your arg).
  const matches = await card.evaluate(
    (el, expected) => el.querySelector('.price')?.textContent?.includes(expected),
    '$29',
  );
  expect(matches).toBe(true);
});

Pattern 4 — evaluateHandle for non-serializable objects

When the value cannot be serialized (the window, a DOM node, a Map) but you need to keep using it, get a handle and pass it back into later evaluate calls.

test('keeps a live handle to a non-serializable object', async ({ page }) => {
  await page.goto('https://example.com');

  // window is not serializable — get a handle instead.
  const windowHandle = await page.evaluateHandle(() => window);

  // Reuse the handle as an argument in a later evaluate.
  const innerWidth = await page.evaluate((w) => (w as Window).innerWidth, windowHandle);
  expect(innerWidth).toBeGreaterThan(0);

  // Handl
Полный SKILL.md на GitHub

Установить Playwright page.evaluate Patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Playwright page.evaluate Patterns?

Teaches the agent when and how to use page.evaluate, evaluateHandle, and exposeFunction in Playwright — passing arguments safely, reading DOM/JS state, and why locators should be preferred for actions.

Как установить скилл Playwright page.evaluate Patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Playwright page.evaluate Patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Playwright page.evaluate Patterns с