日本語

How to Fix Playwright “Element is outside of the viewport”

​​Playwright​E2E Testing,Troubleshooting,TypeScript

When a Playwright E2E test fails in click() with element is outside of the viewport in the Call log, the element you want to press is outside the viewport, and scrolling cannot bring it back into the screen. One example is a button inside a hamburger-style menu that is kept off-screen with a CSS transform while it is closed. If you press the button that opens the menu first, the element moves into the viewport and the error goes away.

I reproduced this error in a test environment and included the message exactly as it was printed. I also confirmed that force: true and scrollIntoViewIfNeeded() do not fix it, and that toBeVisible() cannot tell this state apart.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, @playwright/test 1.63.0 (Chromium 158.0.8127.36, headless), and TypeScript 5.9.3. The page under test was built in place with page.setContent(), not an external site. I did not try Firefox or WebKit, Playwright in other languages such as Python, or ways of placing an element off-screen other than transform.

Reproducing the error

The test page has a menu that slides in from the left. The menu (#drawer) is position: fixed at the left edge of the screen. While it is closed, transform: translateX(-100%) shifts it left by its own width, so it sits outside the screen. Pressing the Menu button adds the open class, and the menu slides into the screen over 0.3 seconds. Pressing the Settings button inside it changes the text of the status. This is the content of tests/page.ts.

ts
// Menu that slides in from the left (it stays off-screen to the left while closed)
export const html = `
<style>
  body { margin: 0; font-family: sans-serif; }
  header { padding: 12px 16px; }
  #drawer {
    position: fixed; top: 0; left: 0; width: 240px; height: 100vh;
    padding: 16px; box-sizing: border-box; background: #eefafd;
    transform: translateX(-100%); transition: transform 0.3s;
  }
  #drawer.open { transform: translateX(0); }
</style>
<header>
  <button id="menu">メニュー</button>
  <p id="status">設定は開いていません</p>
</header>
<nav id="drawer">
  <button id="settings">設定</button>
</nav>
<script>
  document.querySelector('#menu').addEventListener('click', () => {
    document.querySelector('#drawer').classList.add('open');
  });
  document.querySelector('#settings').addEventListener('click', () => {
    document.querySelector('#status').textContent = '設定を開きました';
  });
</script>
`;

The configuration file (playwright.config.ts) uses Chromium and a screen size of 800px wide and 600px high.

ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  reporter: 'list',
  use: {
    browserName: 'chromium',
    viewport: { width: 800, height: 600 },
  },
});

I wrote a test in tests/bad.spec.ts that presses the Settings button without opening the menu first.

ts
import { test, expect } from '@playwright/test';
import { html } from './page';

test('設定ボタンを押す', async ({ page }) => {
  await page.setContent(html);
  await page.getByRole('button', { name: '設定' }).click();
  await expect(page.locator('#status')).toHaveText('設定を開きました');
});

When I ran npx playwright test tests/bad.spec.ts, the test waited until the 30-second test timeout and then failed as follows (exit code 1). The output is unchanged, except that the working directory path is replaced with /path/to/app.

text
Running 1 test using 1 worker

  ✘  1 tests/bad.spec.ts:4:5 › 設定ボタンを押す (30.0s)


  1) tests/bad.spec.ts:4:5 › 設定ボタンを押す ──────────────────────────────────────────────────────────────

    Test timeout of 30000ms exceeded.

    Error: locator.click: Test timeout of 30000ms exceeded.
    Call log:
      - waiting for getByRole('button', { name: '設定' })
        - locator resolved to <button id="settings">設定</button>
      - attempting click action
        2 × waiting for element to be visible, enabled and stable
          - element is visible, enabled and stable
          - scrolling into view if needed
          - done scrolling
          - element is outside of the viewport
        - retrying click action
        - waiting 20ms
        2 × waiting for element to be visible, enabled and stable
          - element is visible, enabled and stable
          - scrolling into view if needed
          - done scrolling
          - element is outside of the viewport
        - retrying click action
          - waiting 100ms
        58 × waiting for element to be visible, enabled and stable
           - element is visible, enabled and stable
           - scrolling into view if needed
           - done scrolling
           - element is outside of the viewport
         - retrying click action
           - waiting 500ms


      4 | test('設定ボタンを押す', async ({ page }) => {
      5 |   await page.setContent(html);
    > 6 |   await page.getByRole('button', { name: '設定' }).click();
        |                                                  ^
      7 |   await expect(page.locator('#status')).toHaveText('設定を開きました');
      8 | });
      9 |
        at /path/to/app/tests/bad.spec.ts:6:50

    Error Context: test-results/bad-設定ボタンを押す/error-context.md

  1 failed
    tests/bad.spec.ts:4:5 › 設定ボタンを押す ───────────────────────────────────────────────────────────────

The first line of the error is Test timeout of 30000ms exceeded., which alone does not explain the cause. The clue is in the Call log.

Reading the Call log

The Call log lists, in order, what Playwright did inside click(). According to the locator.click() documentation, click() waits until the element is ready to be pressed, scrolls it into view if needed, and then presses the center of the element with the mouse.

In this output, the check element is visible, enabled and stable passed, meaning the element was visible, enabled, and not moving. The following scrolling into view if needed and done scrolling lines show that scrolling also finished. Even so, the last line was element is outside of the viewport, so no press position inside the screen could be found. Playwright kept retrying this (58 × is a summary showing that the same sequence repeated 58 times), and the test timed out after 30 seconds.

The hard part is that the element is "visible" yet outside the screen. Playwright treats an element as "visible" when its size is not zero and its visibility is not hidden (the explanation of the visibility check). It does not check whether the element is within the viewport. A button inside a menu that is only shifted by transform keeps its size and visibility, so it is judged to be "visible".

Two menu states placed one above the other. When closed, the menu and the Settings button inside it are outside the left edge of the browser's viewport, so click() fails with element is outside of the viewport. When the Menu button is pressed to open it, the menu moves into the viewport and click() can press the button. (The labels in the image are in Japanese.)
A button inside a closed menu is outside the viewport

Neither force: true nor scrolling fixes it

I also confirmed in the test environment the two approaches people often try when a click does not work.

The first is click({ force: true }). The force option of click() skips the check that the element is ready to be pressed. I changed click() to click({ force: true }) in a test (tests/force.spec.ts) and ran it. It failed immediately (141ms) without waiting.

text
    Error: locator.click: Element is outside of the viewport
    Call log:
      - waiting for getByRole('button', { name: '設定' })
        - locator resolved to <button id="settings">設定</button>
      - attempting click action
        - scrolling into view if needed
        - done scrolling

With force: true, the first line of the error becomes Element is outside of the viewport itself. Skipping the check does not change the fact that the mouse press position is outside the screen, so the press cannot happen. Because the cause appears without waiting for the timeout, this option is useful when you want to find out which error is actually stopping the test.

The second is to call scrollIntoViewIfNeeded() before pressing.

ts
test('スクロールしてから設定ボタンを押す', async ({ page }) => {
  await page.setContent(html);
  const settings = page.getByRole('button', { name: '設定' });
  await settings.scrollIntoViewIfNeeded();
  await settings.click();
  await expect(page.locator('#status')).toHaveText('設定を開きました');
});

As with the first test, this timed out after 30 seconds, and the Call log repeatedly showed element is outside of the viewport. click() already scrolls by itself, so scrolling in advance gives the same result.

Open the menu first, then press

The fix is to operate the page in the same order a user would. First press the Menu button to open the menu, then press the Settings button. This is tests/good.spec.ts.

ts
import { test, expect } from '@playwright/test';
import { html } from './page';

test('メニューを開いてすぐ設定ボタンを押す', async ({ page }) => {
  await page.setContent(html);
  await page.getByRole('button', { name: 'メニュー' }).click();
  await page.getByRole('button', { name: '設定' }).click();
  await expect(page.locator('#status')).toHaveText('設定を開きました');
});

When I ran it, the test passed and the error was gone.

text
Running 1 test using 1 worker

  ✓  1 tests/good.spec.ts:4:5 › メニューを開いてすぐ設定ボタンを押す (543ms)

  1 passed (1.1s)

The test tries to press the Settings button while the menu is still sliding in over 0.3 seconds, but it did not fail even without any extra wait code. Playwright checks that the element is stable before pressing it. It treats an element as "stable" when its position and size do not change between two consecutive frames, so it waits instead of pressing while the element is still moving.

Checking whether an element is outside the viewport with toBeInViewport()

When you want a test to confirm that the menu has opened, toBeVisible() is not suitable. I tried toBeVisible() and toBeInViewport() on the Settings button inside the closed menu, and the results differed.

ts
test('閉じたメニューの設定ボタンは toBeVisible を通る', async ({ page }) => {
  await page.setContent(html);
  await expect(page.getByRole('button', { name: '設定' })).toBeVisible();
});

test('閉じたメニューの設定ボタンは toBeInViewport を通らない', async ({ page }) => {
  await page.setContent(html);
  await expect(page.getByRole('button', { name: '設定' })).toBeInViewport();
});

test('メニューを開くと設定ボタンは toBeInViewport を通る', async ({ page }) => {
  await page.setContent(html);
  await page.getByRole('button', { name: 'メニュー' }).click();
  await expect(page.getByRole('button', { name: '設定' })).toBeInViewport();
});
text
Running 3 tests using 1 worker

  ✓  1 tests/visible.spec.ts:4:5 › 閉じたメニューの設定ボタンは toBeVisible を通る (123ms)
  ✘  2 tests/visible.spec.ts:9:5 › 閉じたメニューの設定ボタンは toBeInViewport を通らない (5.1s)
  ✓  3 tests/visible.spec.ts:14:5 › メニューを開くと設定ボタンは toBeInViewport を通る (398ms)

toBeVisible() passes even for the button inside the closed menu. toBeInViewport() waited 5 seconds and then failed, and the error showed Received: viewport ratio 0 (the fraction of the element overlapping the viewport is 0). After opening the menu, it passes. As described in the toBeInViewport() documentation, it checks whether the element overlaps the viewport. To confirm that the menu has opened, use toBeInViewport().

Pressing with dispatchEvent('click') makes the test pass

Using dispatchEvent('click') lets you "press" the Settings button without opening the menu. The locator.dispatchEvent() documentation also says it sends a click event regardless of whether the element is visible.

ts
test('メニューを開かずに dispatchEvent で押す', async ({ page }) => {
  await page.setContent(html);
  await page.getByRole('button', { name: '設定' }).dispatchEvent('click');
  await expect(page.locator('#status')).toHaveText('設定を開きました');
});

In my test, this passed without opening the menu (165ms). It does not press the button with the mouse; it sends the event directly to the element. So a bug where the menu does not open would go unnoticed. For a test that should confirm the same operation a user performs, use the fix above: open the menu, then press with click().

​Posted by 86