From c479366c8d3d2a99e6ddd999b8c331cafb34d89c Mon Sep 17 00:00:00 2001 From: "microsoft-playwright-automation[bot]" <203992400+microsoft-playwright-automation[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:09:24 +0000 Subject: [PATCH] fix(route): serialize lone surrogates in JSON post data Fixes: https://github.com/microsoft/playwright-python/issues/3374 --- playwright/_impl/network.py | 14 ++++++++++++-- tests/async/python/test_network.py | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/playwright/_impl/network.py b/playwright/_impl/network.py index 1b65871a8..719bb8eab 100644 --- a/playwright/_impl/network.py +++ b/playwright/_impl/network.py @@ -1383,8 +1383,18 @@ def headers_array(self) -> HeadersArray: def _json_stringify(value: Any) -> str: - # JSON.stringify(value): no spaces, and no escapes for non-ASCII characters. - return json.dumps(value, allow_nan=False, ensure_ascii=False, separators=(",", ":")) + # Python: JSON.stringify escapes lone surrogates, but preserves valid pairs. + def escape_surrogate(match: "re.Match[str]") -> str: + text = match[0] + if len(text) == 2: + return text.encode("utf-16-le", "surrogatepass").decode("utf-16-le") + return f"\\u{ord(text):04x}" + + return re.sub( + r"[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]", + escape_surrogate, + json.dumps(value, allow_nan=False, ensure_ascii=False, separators=(",", ":")), + ) def _js_typeof(value: Any) -> str: diff --git a/tests/async/python/test_network.py b/tests/async/python/test_network.py index f44ae66b1..b0c31b19e 100644 --- a/tests/async/python/test_network.py +++ b/tests/async/python/test_network.py @@ -86,6 +86,7 @@ async def test_response_headers_should_work(page: Page, server: Server) -> None: async def test_should_parse_the_json_post_data_when_content_type_header_is_missing( page: Page, server: Server ) -> None: + # Regression test for https://github.com/microsoft/playwright-python/issues/3374. await page.goto(server.EMPTY_PAGE) async with page.expect_request("**/*") as request_info: await page.evaluate( @@ -103,6 +104,20 @@ async def test_should_parse_the_json_post_data_when_content_type_header_is_missi assert "content-type" not in request.headers assert request.post_data_json == {"value": 42} + route_future: "asyncio.Future[Route]" = asyncio.Future() + await page.route("**/title.html", lambda route: route_future.set_result(route)) + await page.evaluate("() => { fetch('/title.html', {method: 'POST'}); }") + route = await route_future + _, server_request = await asyncio.gather( + route.continue_( + post_data={"text": "\ud800|\udfff|\ud83d\ude00|\u00e9|\U0001f600"} + ), + server.wait_for_request("/title.html"), + ) + assert server_request.post_body == ( + '{"text":"\\ud800|\\udfff|\U0001f600|\u00e9|\U0001f600"}'.encode("utf-8") + ) + async def test_response_security_details_none_without_https( page: Page, server: Server