Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

docs: add chrome extension testing example (#14969)

Kaspar Emanuel413258bfac9f
diff --git a/docs/src/chrome-extensions-js-python.md b/docs/src/chrome-extensions-js-python.md
index 507ec17152..8515ff7b7d 100644
--- a/docs/src/chrome-extensions-js-python.md
+++ b/docs/src/chrome-extensions-js-python.md
@@ -94,3 +94,57 @@ def run(playwright):
with sync_playwright() as playwright:
run(playwright)
```
+
+## Testing
+
+To have the extension loaded when running tests you can use a test fixture to set the context. You can also dynamically retrieve the extension id and use it that to load and test the popup page for example.
+
+```typescript
+import { test as base, expect, chromium, BrowserContext } from "@playwright/test";
+import path from "path";
+
+export const test = base.extend<{
+ context: BrowserContext;
+ extensionId: string;
+}>({
+ context: async ({ browserName }, use) => {
+ const browserTypes = { chromium };
+ const pathToExtension = path.join(__dirname, "my-extension");
+ const context = await browserTypes[browserName].launchPersistentContext("", {
+ headless: false,
+ args: [
+ `--disable-extensions-except=${pathToExtension}`,
+ `--load-extension=${pathToExtension}`,
+ ],
+ });
+ await use(context);
+ await context.close();
+ },
+ extensionId: async ({ context }, use) => {
+ /*
+ // for manifest v2:
+ let [background] = context.backgroundPages()
+ if (!background)
+ background = await context.waitForEvent("backgroundpage")
+ */
+
+ // for manifest v3:
+ let [background] = context.serviceWorkers();
+ if (!background)
+ background = await context.waitForEvent("serviceworker");
+
+ const extensionId = background.url().split("/")[2];
+ await use(extensionId);
+ },
+});
+
+test("example test", async ({ page }) => {
+ await page.goto("https://example.com");
+ await expect(page.locator("body")).toHaveText("Changed by my-extension");
+});
+
+test("popup page", async ({ page, extensionId }) => {
+ await page.goto(`chrome-extension://${extensionId}/popup.html`);
+ await expect(page.locator("body")).toHaveText("my-extension popup");
+});
+```