How to trigger browser extension’s keyboard shortcut in Playwright?

I’m trying to test my browser extension. Pressing Ctrl+Q command injects HTML form into a current page. I want to test this behaviour, but Playwright seems to be unable to trigger it during tests which leads to the test failing. If I press the shortcut manually while the browser instance is running, the form appears correctly. What am I doing wrong?

import test, { chromium, expect } from "@playwright/test";
import path from "path";
import fs from 'fs';

test.use({ browserName: 'chromium' });

test('Open example.com and trigger the popup form', async () => {
  const pathToExtension = path.resolve(__dirname, '..', 'dist');
  const userDataDir = path.resolve(__dirname, '..', 'tmp-profile');

  if (fs.existsSync(userDataDir)) {
    fs.rmSync(userDataDir, { recursive: true, force: true });
  }

  const browserContext = await chromium.launchPersistentContext(userDataDir, {
    headless: false,
    args: [
      `--disable-extensions-except=${pathToExtension}`,
      `--load-extension=${pathToExtension}`
    ]
  });

  const page = await browserContext.newPage();
  await page.goto('https://example.com');
  await page.waitForLoadState('networkidle');

  console.log('Browser launched...');
  
  page.keyboard.press('Control+q'); // doesn't happen

  const popupForm = page.getByLabel('extension-popup-form');
  expect(popupForm).toBeVisible(); // fails here because the form wasn't triggered
  expect(popupForm).toHaveText('https://example.com');

  await popupForm.press('Enter');
  expect(page).toHaveTitle('Blocked | On Pace Extension');

  browserContext.close();
});

I tried this:

  • dispatching event like this:
await page.evaluate(() => {
  document.dispatchEvent(new KeyboardEvent('keydown', {
    key: 'q',
    code: 'KeyQ',
    ctrlKey: true,
    bubbles: true,
    cancelable: true
  }));
});
  • simulated each key press separately in case the automated shortcut was to quick:
  await page.keyboard.down('Control');
  await page.waitForTimeout(800);
  await page.keyboard.press('q');
  await page.waitForTimeout(600);
  await page.keyboard.up('Control');
  • tried focusing on an element of a page before firing the event;
  • tried running the test on https://www.toptal.com/developers/keycode to ensure the codes of pressed keys were correct (they were).
  • tried experimenting with timeout values before running the event:

await page.waitForTimeout(5000);

  • tried manually pressing the command while the browser instance was running to ensure the extension was loaded correctly (it was).