diff --git a/playwright/_impl/network.py b/playwright/_impl/network.py index 1b65871a8..61f69abb3 100644 --- a/playwright/_impl/network.py +++ b/playwright/_impl/network.py @@ -1384,7 +1384,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/page/test_page_route.py b/tests/async/page/test_page_route.py index f22efe7d8..fc383be19 100644 --- a/tests/async/page/test_page_route.py +++ b/tests/async/page/test_page_route.py @@ -1503,6 +1503,37 @@ async def handler(route: Route) -> None: await wait_for_list(page, post_data) assert post_data[0] == POST_BODY +async def test_route_continue_should_handle_lone_surrogates( + page: Page, server: Server +) -> None: + await page.goto(server.EMPTY_PAGE) + + async def handler(route: Route) -> None: + await route.continue_( + post_data={ + "high": "\ud800", + "low": "\udfff", + "pair": "\ud83d\ude00", + "unicode": "é", + "emoji": "😀", + } + ) + + await page.route("**/surrogate", handler) + + with server.expect_request("/surrogate") as request_info: + await page.evaluate( + """async () => { + await fetch('/surrogate', { method: 'POST' }); + }""" + ) + + expected = ( + '{"high":"\\ud800","low":"\\udfff","pair":"😀",' + '"unicode":"é","emoji":"😀"}' + ).encode("utf-8") + assert request_info.value.post_body == expected + async def test_RO_055_should_be_able_to_intercept_every_navigation_to_a_page_controlled_by_service_worker( page: Page, server: Server