Skip to content

[Bug]: route.continue_() fails to encode post_data containing lone surrogate characters #3374

In progress

Description

@himanshug189-sketch

Version

3.12.3

Steps to reproduce

The following example uses only public Playwright Python APIs:

import asyncio
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

from playwright.async_api import async_playwright


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length)
        print("SERVER RECEIVED:", body)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"OK")

    def log_message(self, format, *args):
        pass


async def main():
    server = HTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    url = f"http://127.0.0.1:{server.server_port}/api"

    try:
        async with async_playwright() as p:
            browser = await p.chromium.launch()
            try:
                page = await browser.new_page()

                async def handle_route(route):
                    try:
                        await route.continue_(
                            post_data={"text": "\ud800"}
                        )
                    except Exception as exc:
                        print(type(exc).__name__)
                        print(str(exc))
                        await route.abort()

                await page.route("**/api", handle_route)

                try:
                    await page.evaluate("""
                        async (url) => {
                            const response = await fetch(url, {
                                method: 'POST'
                            });
                            return response.status;
                        }
                    """, url)
                except Exception as exc:
                    print("Browser request failed:", str(exc))

            finally:
                await browser.close()
    finally:
        server.shutdown()
        server.server_close()


asyncio.run(main())

Expected behavior

Playwright should handle lone surrogate characters during JSON serialization consistently with JavaScript's JSON.stringify() behavior.

The request should not fail with a UnicodeEncodeError during route.continue_().

Actual behavior

Calling route.continue_() with post_data containing a lone UTF-16 surrogate character raises:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800'
in position 9: surrogates not allowed

The error occurs while Playwright attempts to encode the serialized request body as UTF-8.

Expected Behavior

Playwright should handle lone surrogate characters during JSON serialization consistently with JavaScript's JSON.stringify() behavior.

The request should not fail with a UnicodeEncodeError during route.continue_().

Additional context

A previous report was discussed in #3369. The maintainer requested a reproduction using public Playwright APIs instead of importing internal helpers.

This reproduction uses only page.route() and route.continue_().

Environment

- Python version: 3.12.3
- Playwright Python version: 0.1.dev1199+g8b4525108.d20261124
- Browser: Chromium
- OS: Ubuntu Linux

Activity

  1. microsoft-playwright-automation commented on Nov 25, 2026

    @microsoft-playwright-automation
  2. microsoft-playwright-automation commented on Nov 25, 2026

    @microsoft-playwright-automation
    Contributor

    Hi, I'm the Playwright bot. I reproduced this and prepared a fix.

    This is a Python client bug, reproduced on all three browsers. On Python 3.12.3 and Playwright Python main at f31e7025d36bebc4b55c2e94f97f26ac92e13067, route.continue_() raises the reported UnicodeEncodeError. The JavaScript client at the pinned driver commit b0e0b7b555e637cc8c0ce94dd98c3be153861333 sends the same JSON successfully.

    The Python serializer leaves lone surrogates unescaped before UTF-8 encoding. The fix escapes them and combines valid surrogate pairs, while keeping ordinary Unicode unchanged.

    Condensed reproduction

    This case uses the existing page and server test fixtures:

    await page.goto(server.EMPTY_PAGE)
    route_future = 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
    _, request = await asyncio.gather(
        route.continue_(
            post_data={"text": "\ud800|\udfff|\ud83d\ude00|\u00e9|\U0001f600"}
        ),
        server.wait_for_request("/title.html"),
    )
    assert request.post_body == (
        '{"text":"\\ud800|\\udfff|\U0001f600|\u00e9|\U0001f600"}'.encode("utf-8")
    )
    Checks

    All runs were headless on Linux with Python 3.12.3 and the commits above.

    Check Chromium Firefox WebKit
    Python regression without the fix UnicodeEncodeError UnicodeEncodeError UnicodeEncodeError
    Python regression with the fix Pass Pass Pass
    JavaScript public-API comparison Pass Pass Pass
    Async and sync route continue, fallback and fulfill files Pass, existing xfail Pass Pass, existing skip and xfail

    The Python network file passes all 15 tests. The route files pass 456 tests across both API flavors, with four existing xfails and two existing skips. Repository lint and mypy playwright pass.

    The first callback-based reproduction timed out on Chromium. Calling continue_() directly on the captured route exposed the encoding error, as shown above.

    WebKit initially lacked system libraries. I supplied Ubuntu libraries in scratch paths without sudo or host changes, selected a matching local Mesa runtime, and bypassed the host-library cache check because it cannot see those local libraries. WebKit then ran successfully.

    Draft PR: #3377

    Triaged on Linux by the Playwright bot - agent run

  3. himanshug189-sketch commented on Nov 25, 2026

    @himanshug189-sketch
    Author

    Hi,

    I've opened a draft PR addressing this issue:

    PR: #3378

    Implementation Details

    The issue was caused by lone surrogate characters remaining unescaped during Python JSON serialization. When route.continue_() attempted to encode the resulting payload as UTF-8, it raised a UnicodeEncodeError.

    The proposed changes include:

    • Updated JSON serialization to escape lone high and low surrogate characters.
    • Preserved valid UTF-16 surrogate pairs correctly.
    • Maintained proper handling of regular Unicode characters and emoji.
    • Added a regression test in tests/async/page/test_page_route.py to verify the actual outgoing request body.

    Validation

    • Regression test passed on Chromium, Firefox, and WebKit.
    • Full test_page_route.py suite: 174 passed, 5 skipped, 1 xfailed.
    • git diff --check completed without errors.

    I also noticed the automation bot's draft PR #3377 for the same issue. My PR provides an implementation with the regression test covered in the page routing test suite.

    I've kept PR #3378 in draft state for now and would appreciate maintainer feedback on the proposed implementation and test placement.

    Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-triage-done

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions