Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Created April 8, 2024 14:27
Show Gist options
  • Save graffhyrum/44aa46ea79c4bb856703e56f7833d9c5 to your computer and use it in GitHub Desktop.
Save graffhyrum/44aa46ea79c4bb856703e56f7833d9c5 to your computer and use it in GitHub Desktop.

Summary

The sendTabUntilFocused function is an asynchronous function in TypeScript that simulates the pressing of the 'Tab' key until a specific element on the webpage is focused. This function is useful in automated testing scenarios where you need to simulate user interactions with a webpage.

Signature

async function sendTabUntilFocused(page: Page, selector: ReturnType<typeof page.locator>): Promise<void>

Parameters

  • page: An instance of the Page class from the Playwright library, representing a single tab in a browser.
  • selector: A Locator object, which is used to interact with the element on the webpage.

Returns

This function does not return any value. It throws an error if the timeout is reached before the element is focused.

Example

const avatarButtonLocator = page.getByTestId('MainToolbarAvatarMenu');
const menuLocator = page.locator(
  '[data-componentid^="ext-avatarmenu-"]:visible',
  {has: avatarButtonLocator}
);

// Use the sendTabUntilFocused function to tab until the menu is focused
await sendTabUntilFocused(page, menuLocator);
async function sendTabUntilFocused(
page: Page,
selector: ReturnType<typeof page.locator>
) {
let found = false;
const start = Date.now();
const timeout = 10 * 1000;
while (!found && start + timeout > Date.now()) {
await page.keyboard.press('Tab');
const maybeFocusedTarget = await selector.elementHandle();
const classList = await maybeFocusedTarget?.getAttribute('class');
if (classList?.includes('x-focused')) found = true;
}
expect(found, 'Target Element was never focused').toBeTruthy();
}
// example
import { chromium, Page } from 'playwright';
async function main() {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// Navigate to your webpage
await page.goto('http://your-webpage.com');
// Get the locator of the element you want to focus
const targetElement = page.locator('#targetElementId');
// Use the sendTabUntilFocused function to tab until the target element is focused
await sendTabUntilFocused(page, targetElement);
// Continue with the rest of your code...
await browser.close();
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment