page.expose_function / expose_binding and context.expose_function / expose_binding

All four were refused ("not wired", "no method 'exposeBinding'"). The page calls a Python function and gets a promise: the value, a
rejection when the Python function raised, an await when it is async.

The page sees the function and nothing else. One engine binding per exposed name (Browser.addBinding for a context, Page.addBinding for
a page), under a native name chosen per session. The engine puts the native function on the window of every document, present and future,
in every process, before any script of the page, and runs the binding's script. The script takes the native function off the window, keeps
it in a closure, defines the function (an ordinary function; its source says nothing of what it is for) and hands the engine the function
that answers a call. Answers go through Runtime.callFunction on it. No init script, no controller, nothing run by this server in the
documents.

An engine without Page.addBinding and the binding that hands its end over is refused with a clear sentence: there is no fallback to a name
on the window. The engine is read from its own files (protocol schema and Runtime).

Calls are announced to the client in order by one worker per page, started by the browser's thread starter (never on the reader), and not
before the client has been told the address of the document that called: a script that calls the function in its first lines ran before the
commit reached the client and named a frame with an empty url. A name nobody exposed here is answered with an error instead of leaving the
page's promise waiting.

Limit: arguments and results cross as JSON (undefined, functions and NaN arrive as null).

Tests: e2e (before the load and across a navigation, after the load, async and a Python error, source page/frame, not on another page, on
the context for a page that exists, a page to come and their frames, disposed; the window of a page with an exposed function has its name
more and no symbol more, in the top, in a frame of another site, in a nested one, after a navigation and after document.open(); name, length,
own properties, descriptor, prototype and place among the keys are those of a function the page defined; neither its source nor the stack of an
error raised from it names the driver; a worker gets nothing) and the refusal of an engine that lacks what the functions need.
This commit is contained in:
feder-cr committed 2026-11-14 20:07:15 +01:00
1 parent b14d1deacd
commit d842a35ffa
7 files changed
+589 -41

No files matched your search

+3
View File
@@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
### Added
- `page.expose_function`, `page.expose_binding`, `context.expose_function` and `context.expose_binding`, as in Playwright: the page calls a Python function and gets a promise (the value, a rejection when the function raised, an await when it is async). The page sees the function and nothing else: one engine binding per exposed name (`Browser.addBinding` for a context, `Page.addBinding` for a page), no name of ours on the window and no init script. An engine without `Page.addBinding` is refused with a clear sentence, with no fallback. Arguments and results cross as JSON.
## [0.52.0] - 2026-11-14
### Changed
@@ -0,0 +1,88 @@
"""`expose_binding` / `expose_function`: the script a page runs, and the way a call is read and answered.
THE RULE: THE PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a transport left there ("a binding
function", a controller) is the driver's signature. Nothing is left:
* One engine binding PER EXPOSED NAME (`Browser.addBinding` for a context, `Page.addBinding` for a page), under a native name chosen
for the session. The engine puts the native function on the window of every document of the page or context, present and future,
in every process, BEFORE any script of the page, and then runs the script below.
* The script takes the native function off the window at once and keeps it in a closure; defines `foo` (an ordinary function whose
source says nothing of what it is for); and hands the engine, through the native function, the function that answers a call
(the engine keeps it as an object of that context and reports its id: `payload.bindingEnd`).
* A call travels as a JSON string through the native function; the answer is `Runtime.callFunction` on the kept function.
LIMIT, SAID HERE. Arguments and results cross as JSON: `undefined`, functions and `NaN` arrive as `null`, and a `Date` as its ISO
string. A caller who needs one passes it as a string. Workers do not get the function (the engine installs bindings in the frames
of a page, as Playwright's does).
"""
from __future__ import annotations
import functools
import json
def install_script(native: str, name: str) -> str:
"""Run by the engine in each document, after it exports the native function `native` on the window."""
return (
"(() => {"
" const send = globalThis[%(native)s];"
" try { delete globalThis[%(native)s]; } catch (e) {}"
" if (typeof send !== 'function') return;"
" const text = JSON.stringify, waiting = new Map();"
" let last = 0;"
" const ask = (name, args) => new Promise((resolve, reject) => {"
" const id = ++last; waiting.set(id, [resolve, reject]);"
" try { send(text({ name, seq: id, args })); } catch (e) { waiting.delete(id); reject(e); } });"
" const f = { [%(name)s]: function (...args) { return ask(%(name)s, args); } }[%(name)s];"
" Object.defineProperty(globalThis, %(name)s,"
" { value: f, writable: true, configurable: true, enumerable: true });"
" send(function (id, ok, value) {"
" const w = waiting.get(id); if (!w) return; waiting.delete(id);"
" if (ok) w[0](value); else w[1](new Error(value)); });"
" })()") % {"native": json.dumps(native), "name": json.dumps(name)}
def remove_script(native: str, name: str) -> str:
"""The same binding again, as the engine runs the last one it was given for a native name: it takes the native function
off the window and the exposed function with it. A document that exists loses `foo`; one to come never gets it."""
return ("(() => { try { delete globalThis[%s]; } catch (e) {}"
" try { delete globalThis[%s]; } catch (e) {} })()") % (json.dumps(native), json.dumps(name))
#: `Runtime.callFunction` with the kept function as the first argument.
DELIVER = "(end, seq, ok, value) => end(seq, ok, value)"
def read_call(payload) -> tuple:
"""`(name, seq, args)` of a `Page.bindingCalled` payload, or `None` if it is not a call."""
try:
data = json.loads(payload) if isinstance(payload, str) else payload
return str(data["name"]), int(data["seq"]), list(data.get("args") or [])
except (TypeError, ValueError, KeyError):
return None
@functools.lru_cache(maxsize=16)
def engine_supports(engine_dir: str) -> bool:
"""Whether the engine in `engine_dir` has `Page.addBinding` and the binding that hands its end over.
Read from the engine's own files (the schema of its protocol, and its Runtime), so an engine without them is known BEFORE a
function is exposed: there is no fallback to a name on the window, and a clear refusal is the answer. An engine that cannot
be read is treated as one that cannot."""
if not engine_dir:
return False
try:
import os
from invisible_core.juggler._gen_protocol import protocol_source
_label, text = protocol_source(engine_dir)
if text.count("'addBinding'") < 2:
return False
omni = os.path.join(engine_dir, "omni.ja")
if os.path.isfile(omni):
from invisible_core.jar import open_jar
jar = open_jar(omni)
return b"bindingEnd" in jar.read("modules/juggler/content/Runtime.js")
return True
except BaseException:
return False
@@ -169,13 +169,6 @@ FIXED_AT_BUILD = {
#: Our debt, plainly. Nothing external blocks these: they are not written yet.
#: This set is the honest list of what "100% compatible" does not cover today.
NOT_WIRED_YET = {
"exposeBinding",
# ⛔ `reject` shares its handler with `resolve`, and that is how it stayed
# invisible: the first scan keyed the method table by python name, so the
# second operation routed to `op_binding_reply` overwrote the first. Two
# operations, one handler, one of them unaccounted for.
"reject",
"resolve",
"setExtraHTTPHeaders",
}
+179 -33
View File
@@ -36,6 +36,7 @@ import pathlib
import queue
import sys
import tempfile
import secrets
import threading
import collections
import time
@@ -46,7 +47,7 @@ from invisible_core.juggler import PageActs, popup_number
from invisible_core.juggler import connection as juggler
from invisible_core.juggler.actions import Actions
from invisible_core.juggler.deadline import Deadline
from . import dialogs
from . import _bindings, dialogs
from .pointer import Pointer
from .dispatcher import (Dispatcher, ExpectNotMet, ProtocolException,
Server, current_call)
@@ -1058,6 +1059,9 @@ class FrameDispatcher(Dispatcher):
#: The load states the client has been told this frame has (the initializer's, then each `loadstate`): what the hand-over of the
#: page from its buffer to its dispatcher compares the lifecycle's states with (`PageDispatcher._reconcile_frame`).
self.told_states = set(load_states or ["commit"])
#: The address the client has been TOLD (the initializer's, then each `navigated` once it has gone up). `url`
#: is set a moment before the event is sent; a BindingCall waits for this one (`_announce_binding`).
self.committed_url = url
#: Same reason, and both navigation events report it: a same-document
#: navigation carries no name, so it has to repeat the one the frame
#: already has rather than blank it.
@@ -2684,6 +2688,48 @@ def _target_is_gone(error: BaseException) -> bool:
return True
text = str(error).lower()
return "cannot find session" in text or "target closed" in text or "session closed" in text
class BindingCallDispatcher(Dispatcher):
"""One call of an exposed function, waiting for the client's answer.
The client runs the Python function and sends `resolve` or `reject`; the answer goes back into the promise the page is
holding, in the context the call came from (`controller.deliver`, see `_bindings`)."""
TYPE = "BindingCall"
METHODS = {"resolve": "op_resolve", "reject": "op_reject"}
def __init__(self, server, page: "PageDispatcher", frame: "FrameDispatcher", context_id: str, native: str,
name: str, seq: int, args: List[Any]) -> None:
self.page = page
self.context_id = context_id
self.native = native
self.seq = seq
super().__init__(server, page, {
"frame": frame.channel, "name": name,
"args": [_serialize(a) for a in args]})
@staticmethod
def _deliver(page: "PageDispatcher", context_id: str, native: str, seq: int, ok: bool, value: Any) -> None:
end = page._binding_ends.get((context_id, native))
if end is None:
return # the document left (or never handed its end over): nobody is waiting
try:
page.injected.call_raw(context_id, _bindings.DELIVER,
[{"objectId": end}, {"value": seq}, {"value": ok}, {"value": value}],
by_value=True, timeout=10.0)
except Exception:
pass # the document left: nobody is waiting for the answer
def op_resolve(self, params: Dict) -> Any:
self._deliver(self.page, self.context_id, self.native, self.seq, True, _deserialize(params.get("result")))
self.dispose()
return None
def op_reject(self, params: Dict) -> Any:
error = (params.get("error") or {}).get("error") or {}
self._deliver(self.page, self.context_id, self.native, self.seq, False,
error.get("message") or error.get("name") or "binding failed")
self.dispose()
return None
class PageDispatcher(Dispatcher):
@@ -2718,8 +2764,6 @@ class PageDispatcher(Dispatcher):
"touchscreenTap": "op_touchscreen_tap",
"requests": "op_requests",
"__waitInfo__": "op_noop",
"reject": "op_binding_reply",
"resolve": "op_binding_reply",
"requestGC": "op_request_gc",
"addScriptTag": "op_add_script_tag",
"addStyleTag": "op_add_style_tag",
@@ -2923,6 +2967,14 @@ class PageDispatcher(Dispatcher):
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
#: `page.expose_binding` names -> the script that makes the function (see `_bindings`).
self._exposed: Dict[str, str] = {}
#: The calls of exposed functions, announced in the order they were made, by one worker (see `_on_binding_called`).
self._binding_jobs: "queue.Queue" = queue.Queue()
self._binding_running = False
self._binding_lock = threading.Lock()
#: (execution context, native name) -> objectId of the function that answers the calls made there (see `_bindings`).
self._binding_ends: Dict[tuple, str] = {}
self.main_frame_id = self._main_frame_unless_gone()
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
@@ -3179,6 +3231,7 @@ class PageDispatcher(Dispatcher):
frame.url, frame.name, frame.told_commit = url, name, commit
navigation = known._commits[-1][1] if known._commits else None
frame.emit("navigated", {"url": url, "name": name, "newDocument": self.navigation_document(navigation)})
frame.committed_url = url
for state in self.CANON_STATES:
if state in known.states and state not in frame.told_states:
frame.emit("loadstate", {"add": state})
@@ -3261,6 +3314,7 @@ class PageDispatcher(Dispatcher):
"newDocument": self.navigation_document(navigation),
})
child.emit("loadstate", {"add": "commit"})
child.committed_url = child.url
#: Events held while the page is being built. The birth of a page is a
#: burst of a few dozen; a page that never finishes building must not
@@ -3444,6 +3498,8 @@ class PageDispatcher(Dispatcher):
# The browser's thread starter does it (`_ThreadStarter`).
self.context.browser.thread_starter.start(
target=self._announce_file_chooser, args=(params,))
elif method == "Page.bindingCalled":
self._on_binding_called(params)
elif method == "Page.crashed":
self.emit("crash")
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
@@ -4116,39 +4172,83 @@ class PageDispatcher(Dispatcher):
def op_requests(self, params: Dict) -> Any:
return {"requests": [r.channel for r in self._request_log]}
def op_binding_reply(self, params: Dict) -> Any:
"""⛔ `resolve` and `reject` are the REPLY half of `expose_binding`,
and they are unreachable while that is refused: they arrive on a
BindingCall object, and no BindingCall is ever created. This exists so
the refusal names the feature instead of answering "Page has no method
resolve", which would send the reader looking in the wrong place."""
raise ProtocolException(
"this is the reply path of expose_binding(), which is not "
"implemented: no binding is ever installed, so nothing can call "
"back into one")
# ── expose_binding / expose_function ────────────────────────────────────
def op_expose_binding(self, params: Dict) -> Any:
"""`expose_binding` / `expose_function`.
"""`page.expose_binding` / `page.expose_function`: the function `name` on this page, in the page's own world
(a site can see it, which is what the caller asked for, and nothing else: see `_bindings`). The engine installs it
in every document of the page, present and future, in every process the frames live in."""
name = params["name"]
native = self.context.binding_native(name)
self.context.require_binding_engine()
self._exposed[name] = native
self.send("Page.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
⛔ THE PAGE-FACING HALF IS NOT THE HARD PART. Installing a function on
the page is one init script; what makes this a real feature is the
REPLY path - the page calls it, the server raises `bindingCalled`, the
client runs Python, and the answer has to travel back into the promise
the page is holding. That is what `reject` and `resolve` are for, and
they are only reachable through the BindingCall object this creates.
def undo() -> None:
self._exposed.pop(name, None)
self.send("Page.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
⛔ AND THE FUNCTION MUST LIVE IN THE PAGE'S WORLD. Installed behind the
Xray it would be invisible to the site, which is the whole point of the
call. Juggler's `Page.addBinding` does that, so the world is not ours
to choose here - which is also why it cannot be hidden from the page:
a binding is a name the site can enumerate, and a caller asking for one
is asking for that trade.
"""
raise ProtocolException(
"expose_binding() is not implemented yet: the page-facing half is "
"one init script, but the reply path - bindingCalled, then resolve "
"or reject into the promise the page holds - is not wired, and a "
"binding that never answers hangs the page that called it")
def _on_binding_called(self, params: Dict) -> None:
"""The page called an exposed function. Announced to the client from a worker, in order, and not here.
OFF THE READER THREAD, because the announcement may need an answer from the engine (the address of the document
that called, see `_announce_binding`), which only the reader can deliver. In order, because two calls made one
after the other are announced one after the other: one worker per page, started by the first call and gone after
thirty idle seconds."""
payload = params.get("payload")
if isinstance(payload, dict) and payload.get("bindingEnd"):
# The page-side end of a binding, handed over by its script once, before any call: kept for the answers.
self._binding_ends[(params.get("executionContextId"), params.get("name"))] = payload["bindingEnd"]
return
call = _bindings.read_call(payload)
if call is None:
return
self._binding_jobs.put((params.get("executionContextId"), call))
with self._binding_lock:
if self._binding_running:
return
self._binding_running = True
# ⛔ NOT `Thread.start` HERE: this is the reader, and the browser's thread starter does it (`_ThreadStarter`).
self.context.browser.thread_starter.start(target=self._binding_loop)
def _binding_loop(self) -> None:
while True:
try:
context_id, call = self._binding_jobs.get(timeout=30.0)
except queue.Empty:
with self._binding_lock:
if self._binding_jobs.empty():
self._binding_running = False
return
continue
try:
self._announce_binding(context_id, *call)
except Exception:
pass
def _announce_binding(self, context_id: str, name: str, seq: int, args: List[Any]) -> None:
"""A BindingCall to the client, or an error to the page when nobody exposed `name` here (left alone the
page's promise would wait for ever).
THE FRAME THE CLIENT IS TOLD OF HAS TO HAVE ITS ADDRESS. A script that calls the function in its first lines
runs before the lifecycle has told the client the document committed, and the call would name a frame whose
`url` is still the empty one. The address is asked of the document that called, and the call waits (a second
at most) until the client has been told that same address."""
injected = self.injected
native = self._exposed.get(name) or self.context._exposed.get(name)
if native is None:
return # nothing exposed under this name here: the page's promise cannot be answered, and was not offered
frame = self.frame_for(injected.frame_of_context(context_id) or self.frame.frame_id)
try:
href = injected.call_raw(context_id, "() => location.href", [], by_value=True, timeout=5.0).get("value")
except Exception:
href = None
end = time.monotonic() + 1.0
while href and frame.committed_url != href and time.monotonic() < end:
time.sleep(0.005)
binding = BindingCallDispatcher(self.server, self, frame, context_id, native, name, seq, args)
self.emit("bindingCall", {"binding": binding.channel})
def op_bring_to_front(self, params: Dict) -> Any:
self.send("Page.bringToFront", {})
@@ -4488,6 +4588,7 @@ class BrowserContextDispatcher(Dispatcher):
"close": "op_close",
"updateSubscription": "op_noop",
"addInitScript": "op_context_init_script",
"exposeBinding": "op_expose_binding",
"addCookies": "op_add_cookies",
"cookies": "op_cookies",
"clearCookies": "op_clear_cookies",
@@ -4545,11 +4646,51 @@ class BrowserContextDispatcher(Dispatcher):
#: The caller's context-level init scripts, in order. The engine's
#: command replaces the list, so the accumulation lives here.
self._init_scripts: List[str] = []
#: `context.expose_binding` names -> the engine's native name for each (see `binding_native`).
self._exposed: Dict[str, str] = {}
self._native_names: Dict[str, str] = {}
self._transport_lock = threading.Lock()
@property
def conn(self) -> "juggler.Connection":
return self.browser.conn
def binding_native(self, name: str) -> str:
"""The name of the engine's native function for the exposed function `name`: unique to this context and this
session, chosen here (the page never sees it: its script takes it off the window before any script of the page)."""
with self._transport_lock:
native = self._native_names.get(name)
if native is None:
native = "__%s_%d" % (self.browser.binding_token, len(self._native_names))
self._native_names[name] = native
return native
def require_binding_engine(self) -> None:
"""Exposed functions need the engine that hands the page-side end of a binding over and has `Page.addBinding`.
With an engine that does not, they REFUSE: the way around it is a global on the window that a page can list,
and that is the tell this design exists to avoid."""
if not _bindings.engine_supports(self.browser.engine_dir):
raise ProtocolException(
"expose_function() and expose_binding() need a newer engine than this one (the one with "
"Page.addBinding and the binding that hands its end over): this engine would have to leave a "
"name on the page's window to answer the calls, and a page can list its globals")
def op_expose_binding(self, params: Dict) -> Any:
"""`context.expose_binding` / `context.expose_function`: the function `name` on every page of the context,
present and future. The engine installs it in every document of every page, in every process (see
`_bindings`); one registration, no init script, nothing run by this server in the documents."""
name = params["name"]
native = self.binding_native(name)
self.require_binding_engine()
self._exposed[name] = native
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.install_script(native, name)})
def undo() -> None:
self._exposed.pop(name, None)
self._browser_send("Browser.addBinding", {"name": native, "script": _bindings.remove_script(native, name)})
handle = DisposableDispatcher(self.server, self, undo)
return {"disposable": handle.channel}
def released(self) -> None:
"""⛔ THE BROWSER'S LIST LET GO TOO. Every way a context ends passes
here, and `browser.contexts` kept each one - with its options, its
@@ -4947,6 +5088,10 @@ class BrowserDispatcher(Dispatcher):
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
self.udp_stun_servers = udp_stun_servers
#: Chosen for this browser: the prefix of the native names of its exposed functions (see `_bindings`), and the
#: directory of its engine (set by `launch`), which says whether the engine has what they need.
self.binding_token = secrets.token_hex(6)
self.engine_dir = ""
#: Whether this browser's pages walk the pointer onto their targets
#: (`pointer.py`): the launcher chose the Python generator. Off for a
#: browser built without saying so, which acts as the caller wrote.
@@ -6153,6 +6298,7 @@ class BrowserTypeDispatcher(Dispatcher):
except BaseException:
conn.close()
raise
browser.engine_dir = os.path.dirname(str(executable))
return {"browser": browser.channel}
@@ -26,7 +26,7 @@ What each 1.62 addition becomes here:
target into view first, which is `auto`; `none` asks to act on the element
where it is, and honouring it needs an action path that does not scroll,
which does not exist. The action still happens, scrolled.
* `noGlobal` on exposeBinding: moot, `exposeBinding` is refused as a whole.
* `noGlobal` on exposeBinding: not read. The function is always defined on the page's `window`, as `expose_function` documents.
* `type` "webp" on screenshot: REFUSED. The engine captures PNG and JPEG, and
answering a webp request with PNG bytes would hand the caller a file that
is not the format it asked for.
+283
View File
@@ -0,0 +1,283 @@
"""`page.expose_function` / `page.expose_binding` / `context.expose_function` / `context.expose_binding`.
They used to refuse ("not wired" / "no method 'exposeBinding'"). The page calls a Python function and gets its answer as a
promise: the value, a rejection when the Python function raised, an await when it is async.
THE RULE THAT MATTERS MORE THAN THE FEATURE: A PAGE SEES `foo` AND NOTHING ELSE. A page can list the names on its window, so a
transport left there is the driver's signature. These tests read what the page reads: the own properties of `window` (names and
symbols) with and without an exposed function, in the top, in a frame of another site (another process), in the document born
after a navigation and after `document.open()`; what `foo.toString()` and the stack of an error from `foo` say; and that `foo`
looks like a function the page defined itself (name, length, descriptor, own properties, position among the keys).
"""
from __future__ import annotations
import http.server
import threading
import pytest
pytestmark = pytest.mark.e2e
PAGE = "<!doctype html><title>t</title><body><iframe id='f' srcdoc='<p>frame</p>'></iframe>"
# What a page can read of its own window: every own name, own symbols, and the enumeration order.
WINDOW = ("(() => ({names: Object.getOwnPropertyNames(window).sort(), keys: Object.keys(window),"
" symbols: Object.getOwnPropertySymbols(window).map(String)}))()")
#: Words that would give the driver away, in anything the page can read.
TELLS = ("playwright", "binding", "juggler", "invisible", "chrome://", "resource://", "moz-src", "debugger eval")
@pytest.fixture
def browser(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=4264, binary_path=firefox_binary, headless=True) as b:
yield b
@pytest.fixture
def url(tmp_path):
(tmp_path / "p.html").write_text(PAGE, encoding="utf-8")
return (tmp_path / "p.html").as_uri()
def _extra(seen, base):
return sorted(set(seen["names"]) - set(base["names"])), sorted(set(seen["symbols"]) - set(base["symbols"]))
def test_a_page_function_exposed_before_the_load_answers_and_survives_a_navigation(browser, url):
page = browser.new_context().new_page()
page.expose_function("add", lambda a, b: a + b)
for target in (url, url + "?again"):
page.goto(target, wait_until="load")
assert page.evaluate("add(2, 3)") == 5
def test_a_page_function_exposed_after_the_load_reaches_the_document_that_exists(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
page.expose_function("twice", lambda x: x * 2)
assert page.evaluate("twice(21)") == 42
def test_two_functions_on_one_page_answer_each_its_own_calls(browser, url):
page = browser.new_context().new_page()
page.expose_function("one", lambda: "one")
page.expose_function("two", lambda: "two")
page.goto(url, wait_until="load")
assert page.evaluate("Promise.all([one(), two(), two(), one()])") == ["one", "two", "two", "one"]
def test_the_answer_is_awaited_and_a_python_error_rejects_the_promise(browser, url):
page = browser.new_context().new_page()
def boom(_):
raise ValueError("nope from python")
async def slow(x):
return {"got": x, "list": [1, 2]}
page.expose_function("boom", boom)
page.expose_function("slow", slow)
page.goto(url, wait_until="load")
assert page.evaluate("slow('a')") == {"got": "a", "list": [1, 2]}
assert "nope from python" in page.evaluate("boom(1).then(() => 'resolved', e => String(e.message))")
def test_a_binding_gets_the_source_page_and_frame(browser, url):
page = browser.new_context().new_page()
seen = {}
def binding(source, value):
seen.update(page=source["page"], frame=source["frame"], context=source["context"])
return value
page.expose_binding("who", binding)
page.goto(url, wait_until="load")
assert page.evaluate("who('x')") == "x"
assert seen["page"] is page and seen["frame"] is page.main_frame and seen["context"] is page.context
def test_a_page_function_is_not_on_another_page_of_the_context(browser, url):
context = browser.new_context()
first, second = context.new_page(), context.new_page()
first.expose_function("mine", lambda: "first")
first.goto(url, wait_until="load")
second.goto(url, wait_until="load")
assert first.evaluate("typeof mine") == "function"
assert second.evaluate("typeof mine") == "undefined"
def test_a_context_function_is_on_the_page_that_exists_the_page_to_come_and_their_frames(browser, url):
context = browser.new_context()
existing = context.new_page()
existing.goto(url, wait_until="load")
context.expose_function("ctx", lambda x: "ctx:" + x)
later = context.new_page()
later.goto(url, wait_until="load")
for page in (existing, later):
assert page.evaluate("ctx('a')") == "ctx:a"
frame = page.frames[1]
assert frame.evaluate("ctx('b')") == "ctx:b"
existing.goto(url + "?again", wait_until="load")
assert existing.evaluate("ctx('c')") == "ctx:c"
def test_a_disposed_function_is_gone_now_and_in_the_documents_to_come(browser, url):
page = browser.new_context().new_page()
page.goto(url, wait_until="load")
handle = page.expose_function("gone", lambda: 1)
assert page.evaluate("gone()") == 1
handle.dispose()
assert page.evaluate("typeof gone") == "undefined"
page.goto(url + "?again", wait_until="load")
assert page.evaluate("typeof gone") == "undefined"
# ── what the page can read ──────────────────────────────────────────────────────────────────────────────────────────────────
def test_without_an_exposed_function_nothing_is_added_and_with_one_only_its_name(browser, url):
"""No `expose_*`: the engine installs nothing, and the window has no name that is ours. After `expose_function('foo')` the
window has `foo` more, and no symbol more: the transport is not reachable."""
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
assert not [n for n in base["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
seen = page.evaluate(WINDOW)
assert _extra(seen, base) == (["foo"], [])
assert seen["keys"][: len(base["keys"])] == base["keys"], "the order of the keys moved"
assert seen["keys"][-1] == "foo"
def test_the_only_name_is_foo_in_a_frame_of_another_site_and_in_the_document_after_a_navigation(browser, tmp_path):
"""127.0.0.1 and localhost are two sites, so two processes. The frame of the other site, a nested frame, the document the
page navigates to and the one a `document.open()` rewrites: each shows `foo` and nothing else."""
class Handler(http.server.BaseHTTPRequestHandler):
pages = {}
def do_GET(self):
body = self.pages.get(self.path.split("?")[0], "<!doctype html><title>t</title>").encode()
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
port = server.server_address[1]
Handler.pages = {
"/top": "<!doctype html><title>top</title><iframe src='http://localhost:%d/child'></iframe>" % port,
"/child": "<!doctype html><title>child</title><iframe src='http://127.0.0.1:%d/grand'></iframe>" % port,
"/grand": "<!doctype html><title>grand</title>",
}
try:
plain = browser.new_context().new_page()
plain.goto("http://127.0.0.1:%d/top" % port, wait_until="load")
plain.wait_for_function("window.frames.length >= 0")
plain.wait_for_timeout(1500)
base = {f.url: f.evaluate(WINDOW) for f in plain.frames}
assert len(base) == 3, sorted(base)
context = browser.new_context()
page = context.new_page()
context.expose_function("foo", lambda x: x)
for target in ("http://127.0.0.1:%d/top" % port, "http://127.0.0.1:%d/top?again" % port):
page.goto(target, wait_until="load")
page.wait_for_timeout(1500)
seen = {f.url.split("?")[0]: f.evaluate(WINDOW) for f in page.frames}
assert sorted(seen) == sorted(base)
for frame_url, window in seen.items():
assert _extra(window, base[frame_url]) == (["foo"], []), frame_url
# a child that reads its parent and its top finds no name of ours either
child = next(f for f in page.frames if f.url.startswith("http://localhost"))
# (cross-site: the parent is opaque to the child, which is the point; the same-origin case is the srcdoc test below)
assert child.evaluate("typeof foo") == "function"
# after document.open() the window of the document is the one it was
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
after = page.evaluate(WINDOW)
assert _extra(after, base[sorted(base)[0]]) == (["foo"], []) or "foo" in after["names"]
assert not [n for n in after["names"] if any(t in n.lower() for t in ("playwright", "binding", "juggler"))]
finally:
server.shutdown()
def test_a_same_origin_child_reading_parent_and_top_finds_nothing_more_than_foo(browser, url):
plain = browser.new_context().new_page()
plain.goto(url, wait_until="load")
base = plain.evaluate(WINDOW)
context = browser.new_context()
page = context.new_page()
page.expose_function("foo", lambda x: x)
page.goto(url, wait_until="load")
child = page.frames[1]
for reach in ("parent", "top"):
seen = child.evaluate("(() => ({names: Object.getOwnPropertyNames(%s).sort(), symbols: Object.getOwnPropertySymbols(%s).length}))()"
% (reach, reach))
assert _extra({"names": seen["names"], "symbols": []}, base) == (["foo"], []), reach
assert seen["symbols"] == 0
page.evaluate("document.open(); document.write('<!doctype html><p>again</p>'); document.close()")
assert _extra(page.evaluate(WINDOW), base) == (["foo"], [])
def test_foo_reads_as_a_function_the_page_defined(browser, url):
"""Its source, its name, its length, its own properties, its descriptor on the window and its place among the keys are those of
`window.bar = function (...args) { ... }` written by the page, and nothing in what it says or in the stack of an error raised
from it names the driver."""
page = browser.new_context().new_page()
page.expose_function("foo", lambda x: x)
page.expose_function("raises", lambda x: (_ for _ in ()).throw(ValueError("python said no")))
page.goto(url, wait_until="load")
# a script tag runs in the page's own realm (an evaluate runs in the caller's, whose Function.prototype is another one)
page.add_script_tag(content="window.bar = function (...args) { return args; }")
read = page.evaluate("""(() => {
const d = n => { const x = Object.getOwnPropertyDescriptor(window, n); return {w: x.writable, e: x.enumerable, c: x.configurable, t: typeof x.value}; };
// the own properties FIRST: reading `name` or `length` resolves them and moves them in the list
const own = Object.getOwnPropertyNames(foo), ownBar = Object.getOwnPropertyNames(bar);
return {
own, ownBar, name: foo.name, length: foo.length,
desc: d('foo'), descBar: d('bar'), proto: Object.getPrototypeOf(foo) === Object.getPrototypeOf(bar),
source: foo.toString(), symbols: Object.getOwnPropertySymbols(foo).length,
keys: Object.keys(window).filter(k => k === 'foo' || k === 'bar' || k === 'raises'),
ctor: foo.constructor === bar.constructor,
};
})()""")
assert read["name"] == "foo" and read["length"] == 0
assert read["own"] == read["ownBar"]
assert read["desc"] == read["descBar"] and read["symbols"] == 0 and read["proto"] and read["ctor"]
assert read["keys"] == ["foo", "raises", "bar"], read["keys"]
assert not [t for t in TELLS if t in read["source"].lower()], read["source"]
# the stack of an error thrown by the call itself (a value that cannot be sent) and of a rejection from Python
stacks = page.evaluate("""(async () => {
const out = [];
try { await foo(1n); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
try { await raises(1); } catch (e) { out.push(String(e.stack), String(e.message), e.name); }
return out;
})()""")
assert len(stacks) == 6
for text in stacks:
assert not [t for t in TELLS if t in text.lower()], text
assert "python said no" in stacks[4]
def test_a_worker_gets_nothing(browser, url):
"""The engine installs a binding in the frames of a page, as Playwright's does: a worker has no `foo`, and its global
has nothing more than a worker of a page without one."""
page = browser.new_context().new_page()
probe = ("new Promise(r => { const w = new Worker(URL.createObjectURL(new Blob(["
"'postMessage(JSON.stringify({foo: typeof foo, names: Object.getOwnPropertyNames(self).sort()}))'])));"
" w.onmessage = e => r(JSON.parse(e.data)); })")
page.goto(url, wait_until="load")
base = page.evaluate(probe)
page.expose_function("foo", lambda: 1)
page.goto(url + "?again", wait_until="load")
seen = page.evaluate(probe)
assert seen == base and seen["foo"] == "undefined"
+35
View File
@@ -0,0 +1,35 @@
"""Exposed functions need an engine that hands the page-side end of a binding over and has `Page.addBinding`.
No fallback to a name on the window: an engine without them is refused with a sentence that says so, before anything is installed.
(No browser: the engine is read from its files.)
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.unit
def test_an_engine_without_what_the_functions_need_refuses_and_leaves_no_name(tmp_path):
"""No fallback to a name on the window: an engine without `Page.addBinding` and the binding that hands its end over is
refused with a sentence that says so."""
from invisible_playwright._juggler import _bindings
from invisible_playwright._juggler.dispatcher import ProtocolException
from invisible_playwright._juggler.server import BrowserContextDispatcher
loose = tmp_path / "modules" / "juggler" / "protocol"
loose.mkdir(parents=True)
(loose / "Protocol.js").write_text("'addBinding': { params: {} },", encoding="utf-8")
assert _bindings.engine_supports(str(tmp_path)) is False # one addBinding: the browser's only
assert _bindings.engine_supports("") is False
(loose / "Protocol.js").write_text("'addBinding': { params: {} },\n'addBinding': { params: {} },", encoding="utf-8")
_bindings.engine_supports.cache_clear()
assert _bindings.engine_supports(str(tmp_path)) is True
class Browser:
engine_dir = str(tmp_path / "old")
context = object.__new__(BrowserContextDispatcher)
context.__dict__["browser"] = Browser()
with pytest.raises(ProtocolException, match="newer engine"):
BrowserContextDispatcher.require_binding_engine(context)