日本語

How to Grant Notification and Camera Permissions in Playwright Tests

​​Playwright​E2E Testing,getUserMedia,Notifications API,TypeScript

A button that asks to receive browser notifications, or a screen that uses the camera, such as video calls and QR code reading, normally shows a "Allow?" prompt, so automated tests cannot get past it. In Playwright, if you put notifications or camera in the permissions setting, the page opens with that permission already granted. Even on a machine with no real camera, passing a Chromium launch option that streams a dummy video let me test up to the point where the video is received.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, and @playwright/test 1.63.0. I wrote the tests in TypeScript and ran them with Chromium (channel: 'chromium', headless). The test page was served from 127.0.0.1 by the Node.js http module. There is no real camera or microphone. I did not test Firefox or WebKit, a headed browser, or push notifications that use a Service Worker.

The example page

This is a page with one notification button and one camera button. The notification button asks for permission with Notification.requestPermission() and, if permission is granted, shows a notification. The camera button receives video with getUserMedia() and shows the camera name and resolution. If it fails, it shows the error's name and message as they are. I have left out headings and styling, and only included the main parts of the body.

html
<p>Notification.permission:<span id="notify-state">-</span></p>
<button type="button" id="notify">通知を受け取る</button>
<p id="notify-result" role="status">まだ押していません</p>

<p>permissions.query:<span id="camera-state">-</span></p>
<button type="button" id="camera">カメラを使う</button>
<p id="camera-result" role="log">まだ押していません</p>
<video id="preview" autoplay muted playsinline></video>
<script>
  const $ = (id) => document.getElementById(id);
  const showStates = async () => {
    $('notify-state').textContent = Notification.permission;
    const cam = await navigator.permissions.query({ name: 'camera' });
    $('camera-state').textContent = cam.state;
  };
  showStates();

  $('notify').addEventListener('click', async () => {
    const result = await Notification.requestPermission();
    $('notify-state').textContent = Notification.permission;
    if (result !== 'granted') {
      $('notify-result').textContent = `通知は使えません(${result})`;
      return;
    }
    const n = new Notification('猫の手', { body: '新しいコメントがあります' });
    n.onshow = () => { $('notify-result').textContent = `通知を出しました(${n.title})`; };
    n.onerror = () => { $('notify-result').textContent = '通知を出せませんでした'; };
  });

  $('camera').addEventListener('click', async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      const [track] = stream.getVideoTracks();
      const s = track.getSettings();
      $('preview').srcObject = stream;
      $('camera-result').textContent = `カメラを使っています(${track.label}、${s.width}×${s.height})`;
    } catch (err) {
      $('camera-result').textContent = `カメラを使えません(${err.name}:${err.message})`;
    }
    showStates();
  });
</script>

Choose the browser and the fake camera in the config file

Add two settings under use in playwright.config.ts.

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

export default defineConfig({
  testDir: './tests',
  use: {
    baseURL: 'http://127.0.0.1:4173',
    // Use the regular Chromium, which runs in the new headless mode
    channel: 'chromium',
    launchOptions: {
      // Stream a dummy video in place of a real camera
      args: ['--use-fake-device-for-media-stream'],
    },
  },
  webServer: {
    command: 'node server.mjs',
    url: 'http://127.0.0.1:4173',
    reuseExistingServer: false,
  },
});

The first setting, channel: 'chromium', changes which browser is used in headless mode. If you specify nothing, Playwright uses a separate build called "headless shell" in headless mode. With channel: 'chromium', it runs the regular Chromium in the new headless mode, as described in the browsers section of the official documentation.

When I removed this setting, granted both notifications and the camera, and pressed the same buttons, the results were as follows. Both runs used Chromium version 158.0.8127.36.

text
  Notification.permission: denied
  通知: 通知を出せませんでした
  カメラ: カメラを使えません(NotSupportedError:Not supported)

When the notification was created, onerror was called. The page's code only creates a notification when requestPermission() returns granted, so the permission reply was granted. Even so, Notification.permission stayed denied. The camera returned NotSupportedError even though I had set the dummy video option. With channel: 'chromium', both worked, as described in the next sections.

The second setting, --use-fake-device-for-media-stream, is a Chromium launch option. The comment in the Chromium source code describes it as a way to use dummy devices in place of a real camera and microphone. Launch options are passed through launchOptions in use.

Test with notifications granted

Grant the permission with permissions in test.use(). If you write it inside a describe, only the tests in that block get the permission.

ts
test.describe('通知を許可した場合', () => {
  test.use({ permissions: ['notifications'] });

  test('通知を出せる', async ({ page }) => {
    await page.goto('/');
    await expect(page.locator('#notify-state')).toHaveText('granted');
    await page.getByRole('button', { name: '通知を受け取る' }).click();
    await expect(page.locator('#notify-result')).toHaveText('通知を出しました(猫の手)');
  });
});

When the page opened, Notification.permission was granted. When I pressed the button, the notification was created without a prompt, onshow was called, and the text meaning "Notification shown (Neko no Te)" appeared. The label is in Japanese.

The permission names you can use are listed in the browserContext.grantPermissions() reference. notifications, camera, and microphone are all listed there. The same reference says that the permissions you can use depend on the browser and its version, and that some may stop working after an update.

Without permission, the state becomes denied after a while

If you don't set permissions, the page opens with nothing granted. I also checked how notifications behave in that case.

ts
test('通知を許可しないと、しばらくして denied になる', async ({ page }) => {
  await page.goto('/');
  await expect(page.locator('#notify-state')).toHaveText('default');
  const started = Date.now();
  await page.getByRole('button', { name: '通知を受け取る' }).click();
  await expect(page.locator('#notify-result')).toHaveText('通知は使えません(denied)', { timeout: 15000 });
  console.log(`  返事が来るまで: ${((Date.now() - started) / 1000).toFixed(1)}秒`);
  await expect(page.locator('#notify-state')).toHaveText('denied');
});

When the page opened, the state was default. When I pressed the button, requestPermission() returned denied. However, the reply did not come back immediately. I ran it three times, and the time until the reply arrived was 1.8, 1.8, and 2.3 seconds. The default wait time for expect is 5 seconds. The measured times were within that, but I added timeout: 15000 here to leave some margin.

According to MDN's explanation of requestPermission(), default means the user has not decided yet, and an app should treat it the same as denied.

Receive the dummy camera video

For the camera, put camera in permissions.

ts
test.describe('カメラを許可した場合', () => {
  test.use({ permissions: ['camera'] });

  test('ダミーのカメラの映像を受け取れる', async ({ page }) => {
    await page.goto('/');
    await expect(page.locator('#camera-state')).toHaveText('granted');
    await page.getByRole('button', { name: 'カメラを使う' }).click();
    await expect(page.locator('#camera-result')).toHaveText('カメラを使っています(fake_device_0、640×480)');
  });
});

The result of navigator.permissions.query({ name: 'camera' }) was granted when the page opened. When I pressed the button, the camera name was fake_device_0 and the resolution was 640×480. The <video> element showed a dummy video with a green background, a partly cut-off circle, and an elapsed time such as 0:00:01:100.

The notification area shows the text meaning "Notification shown (Neko no Te)" and the camera area shows the text meaning "Using the camera (fake_device_0, 640×480)". Below them is the dummy video with a green background and a partly cut-off circle. The labels are in Japanese.
The screen after granting both notifications and the camera and pressing both buttons

Without camera permission, you get NotAllowedError

If you press the same button without granting the camera permission, getUserMedia() fails.

ts
test('カメラを許可しないと、NotAllowedError になる', async ({ page }) => {
  await page.goto('/');
  await expect(page.locator('#camera-state')).toHaveText('prompt');
  await page.getByRole('button', { name: 'カメラを使う' }).click();
  await expect(page.locator('#camera-result')).toHaveText('カメラを使えません(NotAllowedError:Permission denied)');
  await expect(page.locator('#camera-state')).toHaveText('denied');
});

When the page opened, the state was prompt (not asked yet). When I pressed the button, the text meaning "Camera cannot be used (NotAllowedError: Permission denied)" appeared. After that, the state changed to denied. NotAllowedError is the error that occurs when the user does not allow use of the device, as described in MDN's explanation of the getUserMedia() exceptions. If your page shows guidance when the camera is refused, you can test that state this way.

For camera and microphone together, grant both

On a page that requests video and audio together, such as a video call, camera alone is not enough. I called getUserMedia({ video: true, audio: true }) with only camera granted, and again with microphone added.

ts
test.describe('カメラだけ許可して、マイクも求めた場合', () => {
  test.use({ permissions: ['camera'] });

  test('映像と音声をまとめて求めると失敗する', async ({ page }) => {
    await page.goto('/');
    const result = await page.evaluate(async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        return stream.getTracks().map((t) => `${t.kind}:${t.label}`).join(', ');
      } catch (err) {
        return `${(err as Error).name}:${(err as Error).message}`;
      }
    });
    console.log(`  camera だけ: ${result}`);
    expect(result).toContain('NotAllowedError');
  });

  test('microphone も足すと、両方受け取れる', async ({ page, context }) => {
    await context.grantPermissions(['camera', 'microphone']);
    await page.goto('/');
    const result = await page.evaluate(async () => {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
      return stream.getTracks().map((t) => `${t.kind}:${t.label}`).join(', ');
    });
    console.log(`  camera と microphone: ${result}`);
    expect(result).toContain('audio:');
  });
});

The results were as follows.

text
  camera だけ: NotAllowedError:Permission denied
  camera と microphone: audio:Fake Default Audio Input, video:fake_device_0

Even with video permission, if audio permission was missing, the whole request failed with NotAllowedError. When I added microphone, I could receive both the dummy microphone (Fake Default Audio Input) and the dummy camera. The dummy microphone is also provided by the same --use-fake-device-for-media-stream option.

Grant and revoke permissions in the middle of a test

To change permissions within a single test, use grantPermissions() and clearPermissions() on the context (the browser context).

ts
test('テストの途中で許可を与え、取り消す', async ({ page, context }) => {
  await page.goto('/');
  await context.grantPermissions(['camera']);
  await page.getByRole('button', { name: 'カメラを使う' }).click();
  await expect(page.locator('#camera-result')).toContainText('カメラを使っています');
  await expect(page.locator('#camera-state')).toHaveText('granted');

  await context.clearPermissions();
  await page.reload();
  console.log(`  clearPermissions のあと: ${await page.locator('#camera-state').textContent()}`);
  await page.getByRole('button', { name: 'カメラを使う' }).click();
  await expect(page.locator('#camera-result')).toContainText('NotAllowedError');
});

I granted permission with grantPermissions() after the page had opened, and the camera worked when I pressed the button. After clearPermissions(), reloading the page returned the state to prompt, and pressing the button again gave NotAllowedError.

Results of running the seven tests in a row

I put the seven tests above into one file and ran them three times with the following command. The output of the first run is shown below.

bash
npx playwright test tests/permissions.spec.ts --workers=1
text
Running 7 tests using 1 worker

  ✓  1 tests/permissions.spec.ts:6:3 › 通知を許可した場合 › 通知を出せる (184ms)
  返事が来るまで: 1.8秒
  ✓  2 tests/permissions.spec.ts:14:1 › 通知を許可しないと、しばらくして denied になる (1.9s)
  ✓  3 tests/permissions.spec.ts:27:3 › カメラを許可した場合 › ダミーのカメラの映像を受け取れる (221ms)
  ✓  4 tests/permissions.spec.ts:35:1 › カメラを許可しないと、NotAllowedError になる (196ms)
  clearPermissions のあと: prompt
  ✓  5 tests/permissions.spec.ts:43:1 › テストの途中で許可を与え、取り消す (299ms)
  camera だけ: NotAllowedError:Permission denied
  ✓  6 tests/permissions.spec.ts:60:3 › カメラだけ許可して、マイクも求めた場合 › 映像と音声をまとめて求めると失敗する (110ms)
  camera と microphone: audio:Fake Default Audio Input, video:fake_device_0
  ✓  7 tests/permissions.spec.ts:74:3 › カメラだけ許可して、マイクも求めた場合 › microphone も足すと、両方受け取れる (121ms)

  7 passed (3.8s)

All seven tests passed in all three runs. The total times were 3.8, 3.7, and 4.3 seconds. Only the test that does not grant notifications took a long time, about 1.9 to 2.5 seconds each. The others each took less than 0.3 seconds.

Common mistakes: a misspelled permission name, and launchOptions in a describe

If you write the permission name as notification instead of notifications, the test stops before the page opens, with this error.

text
    Error: browser.newContext: Unknown permission: notification

Also, if you try to use the dummy camera in only some tests and put launchOptions in test.use() inside a describe, no tests start and you get this error.

text
Cannot use({ launchOptions }) in a describe group, because it forces a new worker.
Make it top-level in the test file or put in the configuration file.

As the message says, launchOptions must be written at the top level of the test file or in the configuration file. If you keep it in the config file as in this article and change only the permissions per describe, the differences between tests can be expressed by permissions alone.

​Posted by 86