跳至主要内容

Chrome 扩展

简介

注意

扩展仅在使用持久上下文启动的 Chrome/Chromium 中有效。自行承担使用自定义浏览器参数的风险,因为其中一些参数可能会破坏 Playwright 的功能。

以下代码用于获取位于 ./my-extension 中的 后台页面清单 v2 扩展的句柄。

from playwright.sync_api import sync_playwright, Playwright

path_to_extension = "./my-extension"
user_data_dir = "/tmp/test-user-data-dir"


def run(playwright: Playwright):
context = playwright.chromium.launch_persistent_context(
user_data_dir,
headless=False,
args=[
f"--disable-extensions-except={path_to_extension}",
f"--load-extension={path_to_extension}",
],
)
if len(context.background_pages) == 0:
background_page = context.wait_for_event('backgroundpage')
else:
background_page = context.background_pages[0]

# Test the background page as you would any other page.
context.close()


with sync_playwright() as playwright:
run(playwright)

测试

要使扩展在运行测试时加载,您可以使用测试夹具来设置上下文。您还可以动态检索扩展 ID 并使用它来加载和测试弹出页面,例如。

首先,添加将加载扩展的夹具

conftest.py
from typing import Generator
from pathlib import Path
from playwright.sync_api import Playwright, BrowserContext
import pytest


@pytest.fixture()
def context(playwright: Playwright) -> Generator[BrowserContext, None, None]:
path_to_extension = Path(__file__).parent.joinpath("my-extension")
context = playwright.chromium.launch_persistent_context(
"",
headless=False,
args=[
f"--disable-extensions-except={path_to_extension}",
f"--load-extension={path_to_extension}",
],
)
yield context
context.close()


@pytest.fixture()
def extension_id(context) -> Generator[str, None, None]:
# for manifest v2:
# background = context.background_pages[0]
# if not background:
# background = context.wait_for_event("backgroundpage")

# for manifest v3:
background = context.service_workers[0]
if not background:
background = context.wait_for_event("serviceworker")

extension_id = background.url.split("/")[2]
yield extension_id

然后在测试中使用这些夹具

test_foo.py
from playwright.sync_api import expect, Page


def test_example_test(page: Page) -> None:
page.goto("https://example.com")
expect(page.locator("body")).to_contain_text("Changed by my-extension")


def test_popup_page(page: Page, extension_id: str) -> None:
page.goto(f"chrome-extension://{extension_id}/popup.html")
expect(page.locator("body")).to_have_text("my-extension popup")

无头模式

危险

headless=new 模式未被 Playwright 官方支持,可能会导致意外行为。

默认情况下,Playwright 中 Chrome 的无头模式不支持 Chrome 扩展。要克服此限制,您可以使用以下代码运行 Chrome 的持久上下文以及新的无头模式

conftest.py
path_to_extension = Path(__file__).parent.joinpath("my-extension")
context = playwright.chromium.launch_persistent_context(
"",
headless=False,
args=[
"--headless=new",
f"--disable-extensions-except={path_to_extension}",
f"--load-extension={path_to_extension}",
],
)