Search code examples
playwright

How to ignore that element doesn't exist and skip taking a screenshot?


I would like to take a screenshot of an element that might or might not exist

  const elem = await page.locator('.selector')
  await elem.scrollIntoViewIfNeeded();
  await elem.screenshot({path: 'screenshot.png'});

If the element isn't on the page this results in

elementHandle.screenshot: Timeout 30000ms exceeded.

Is there a way to just ignore the nonexistence and move on?

This behaves the same

const elem = await page.locator('.selector')
if(elem) {
  await elem.scrollIntoViewIfNeeded();
  await elem.screenshot({path: 'screenshot.png'});
}

Solution

  • Try wrapping your logic in try {} catch() {} as the possible throw created by screenshot not existing is going to be passed to catch where it can be ignored, instead crashing runtime.