Skip to content

The headless browser for AI agents and web scraping

Fix puppeteer `exposeFunction` end-to-end: real bindings, preload timing, URL coercion (#166)

Marc Bachmannea89f050cdb3
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index a3e2b43c..dd72551c 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -137,6 +137,11 @@ pub struct Page {
pub intercept_enabled: bool,
pub intercept_block_patterns: Vec<String>,
intercept_tx: Option<tokio::sync::mpsc::UnboundedSender<obscura_js::ops::InterceptedRequest>>,
+ // Scripts to execute in the page's JS context BEFORE any of the page's
+ // own scripts run — the CDP `Page.addScriptToEvaluateOnNewDocument`
+ // contract. Includes `Runtime.addBinding` shims so puppeteer's
+ // `exposeFunction` bindings exist before inline `<script>` tags execute.
+ preload_scripts: Vec<String>,
#[cfg(feature = "stealth")]
pub stealth_client: Option<Arc<StealthHttpClient>>,
}
@@ -181,6 +186,7 @@ impl Page {
intercept_enabled: false,
intercept_block_patterns: Vec::new(),
intercept_tx: None,
+ preload_scripts: Vec::new(),
#[cfg(feature = "stealth")]
stealth_client,
}
@@ -416,6 +422,20 @@ impl Page {
let _ = js.execute_script("<ready-state>", "globalThis.__documentReadyState__ = 'loading';");
}
+ // CDP `Page.addScriptToEvaluateOnNewDocument` contract: preload
+ // sources must run BEFORE any of the page's own scripts. This is
+ // also where puppeteer's `exposeFunction` wrapper installs itself —
+ // if preload runs after page scripts, every early binding call
+ // hits an undefined function and silently no-ops.
+ let preload_sources = self.preload_scripts.clone();
+ if let Some(js) = &mut self.js {
+ for source in &preload_sources {
+ if let Err(e) = js.execute_script_guarded("<preload>", source.as_str()) {
+ tracing::debug!("Preload script error: {}", e);
+ }
+ }
+ }
+
for (i, script) in all_to_execute.iter().enumerate() {
if script.src.is_some() {
if let Some((url, code, resp)) = fetched.remove(&i) {
@@ -616,6 +636,18 @@ impl Page {
if url.scheme() == "about" {
self.navigate_blank();
self.init_js();
+ // Preloads (Page.addScriptToEvaluateOnNewDocument, the
+ // Runtime.addBinding shim) must run on about:blank too —
+ // puppeteer's `browser.newPage()` lands on about:blank and
+ // a follow-up `exposeFunction` is unusable otherwise.
+ let preload_sources = self.preload_scripts.clone();
+ if let Some(js) = &mut self.js {
+ for source in &preload_sources {
+ if let Err(e) = js.execute_script_guarded("<preload>", source.as_str()) {
+ tracing::debug!("Preload script error on about:blank: {}", e);
+ }
+ }
+ }
return Ok(());
}
@@ -1023,6 +1055,18 @@ impl Page {
}
}
+ pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {
+ if let Some(js) = &self.js {
+ js.take_pending_binding_calls()
+ } else {
+ Vec::new()
+ }
+ }
+
+ pub fn set_preload_scripts(&mut self, scripts: Vec<String>) {
+ self.preload_scripts = scripts;
+ }
+
pub async fn process_pending_navigation(&mut self) -> Result<bool, PageError> {
if let Some((url, method, body)) = self.take_pending_navigation() {
self.navigate_with_wait_post(
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index 3c89f5cd..cbc87976 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -272,6 +272,8 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
_ => Err(format!("Unknown domain: {}", domain)),
};
+ drain_binding_calls(ctx);
+
match result {
Ok(value) => CdpResponse::success(req.id, value, req.session_id.clone()),
Err(msg) => {
@@ -281,6 +283,50 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
}
}
+// Drain every page's binding-call queue (filled by op_binding_called when
+// page JS invokes a `Runtime.addBinding` shim) and turn each entry into a
+// Runtime.bindingCalled CDP event that the writer task forwards to the
+// connected client. Called after every dispatch — binding calls only land
+// in the queue while V8 is running inside a CDP handler, so there is no
+// window in which they could pile up without a draining opportunity.
+fn drain_binding_calls(ctx: &mut CdpContext) {
+ // page_id -> session_id (any one session that holds this page).
+ let page_to_session: HashMap<String, String> = ctx
+ .sessions
+ .iter()
+ .map(|(sid, pid)| (pid.clone(), sid.clone()))
+ .collect();
+
+ let mut events: Vec<CdpEvent> = Vec::new();
+ for page in &mut ctx.pages {
+ let calls = page.take_pending_binding_calls();
+ if calls.is_empty() {
+ continue;
+ }
+ let Some(session_id) = page_to_session.get(&page.id).cloned() else {
+ // No session attached — drop the calls; there is no client to
+ // deliver them to.
+ continue;
+ };
+ for (name, payload) in calls {
+ events.push(CdpEvent {
+ method: "Runtime.bindingCalled".into(),
+ // Use executionContextId=2: the default main-frame context
+ // emitted post-navigation (see domains/page.rs phase1).
+ // Puppeteer matches on session_id + binding name and
+ // tolerates any registered context id.
+ params: json!({
+ "name": name,
+ "payload": payload,
+ "executionContextId": 2,
+ }),
+ session_id: Some(session_id.clone()),
+ });
+ }
+ }
+ ctx.pending_events.extend(events);
+}
+
async fn dispatch_send_message_to_target(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
let session_id = req
.params
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rs
index 5751fcaf..4c1ab3c4 100644
--- a/crates/obscura-cdp/src/domains/page.rs
+++ b/crates/obscura-cdp/src/domains/page.rs
@@ -50,6 +50,11 @@ async fn do_navigate(
let frame_id = page.frame_id.clone();
let loader_id = format!("loader-{}", uuid::Uuid::new_v4());
+ // Preloads (addBinding shims, addScriptToEvaluateOnNewDocument sources)
+ // must run BEFORE the page's own scripts (CDP contract). Hand them to
+ // the page so navigate_single can inject them at the right point.
+ page.set_preload_scripts(preload_scripts);
+
let nav_method = params.get("__method").and_then(|v| v.as_str()).unwrap_or("GET");
let nav_body = params.get("__body").and_then(|v| v.as_str()).unwrap_or("");
if nav_method == "POST" && !nav_body.is_empty() {
@@ -58,12 +63,6 @@ async fn do_navigate(
page.navigate_with_wait(url, wait_until).await.map_err(|e| e.to_string())?;
}
- for source in &preload_scripts {
- if let Err(e) = page.execute_preload_script(source) {
- tracing::debug!("Preload script error: {}", e);
- }
- }
-
let reached_network_idle = page.lifecycle.is_network_idle();
let network_events: Vec<_> = page.network_events.drain(..).collect();
let page_url = page.url_string();
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index 3d9c55d2..0e801dc4 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -211,19 +211,50 @@ pub async fn handle(
Ok(json!({}))
}
"addBinding" => {
+ let name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ if !name.is_empty()
+ && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
+ && !name.chars().next().unwrap_or('0').is_ascii_digit()
+ {
+ // The shim forwards every call back to Rust through
+ // op_binding_called; the CDP dispatcher then drains the
+ // queue and emits Runtime.bindingCalled events the same
+ // way Chromium does. Chromium's V8InspectorImpl rejects
+ // calls without exactly one argument and ToString-coerces
+ // that argument before emitting it as the payload — we
+ // match the coercion (`String(arg)`) and silently drop
+ // calls with wrong arity, which is what Chrome does.
+ let shim = format!(
+ "globalThis['{name}'] = function (arg) {{\
+ if (arguments.length !== 1) return;\
+ try {{\
+ const payload = typeof arg === 'string' ? arg : String(arg);\
+ Deno.core.ops.op_binding_called('{name}', payload);\
+ }} catch (e) {{ /* swallow: binding must not throw into page */ }}\
+ }};",
+ name = name,
+ );
+ // Re-install on every navigation: globalThis is wiped on
+ // each new document, and puppeteer registers bindings
+ // once-per-page rather than once-per-document.
+ let key = format!("__obscura_binding__{}", name);
+ ctx.preload_scripts.retain(|(k, _)| k != &key);
+ ctx.preload_scripts.push((key, shim.clone()));
+ // Install on the current page so the binding is usable
+ // immediately, without waiting for the next navigation.
+ if let Some(page) = ctx.get_session_page_mut(session_id) {
+ page.evaluate(&shim);
+ }
+ }
+ Ok(json!({}))
+ }
+ "removeBinding" => {
let name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
if !name.is_empty() {
- if name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
- && !name.chars().next().unwrap_or('0').is_ascii_digit() {
- if let Some(page) = ctx.get_session_page_mut(session_id) {
- let code = format!(
- "if (typeof globalThis.{name} === 'undefined') {{\
- globalThis.{name} = function() {{ return null; }};\
- }}",
- name = name,
- );
- page.evaluate(&code);
- }
+ let key = format!("__obscura_binding__{}", name);
+ ctx.preload_scripts.retain(|(k, _)| k != &key);
+ if let Some(page) = ctx.get_session_page_mut(session_id) {
+ page.evaluate(&format!("delete globalThis['{}'];", name));
}
}
Ok(json!({}))
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 194c85d5..a0501f0f 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -548,12 +548,11 @@ async fn process_with_interception(
// CDP messages via `dispatch` (which also acquires this lock); both
// sides must coordinate or V8 aborts the process at concurrency >= 5.
let _v8_guard = obscura_js::v8_lock::global().lock().await;
+ // Preloads (addBinding shims, addScriptToEvaluateOnNewDocument sources)
+ // must run BEFORE the page's own scripts (CDP contract). Hand them
+ // to the page so navigate_single can inject them at the right point.
+ page.set_preload_scripts(preload_scripts);
let result = page.navigate_with_wait(&url_owned, wait_until).await.map_err(|e| e.to_string());
- for source in &preload_scripts {
- if let Err(e) = page.execute_preload_script(source) {
- tracing::debug!("Preload script error: {}", e);
- }
- }
drop(_v8_guard);
let _ = nav_done_tx.send((page, result)).await;
});
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index d4a2069d..1c8352a3 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -1691,6 +1691,12 @@ _markNative(XMLHttpRequest.prototype.getAllResponseHeaders);
if (typeof URL === 'undefined' || !URL.prototype) {
globalThis.URL = class URL {
constructor(url, base) {
+ // Per WHATWG URL spec, both arguments are stringified — callers
+ // routinely pass `window.location` (Location object) or a URL
+ // instance as `base`. Coerce explicitly so the regex .match() calls
+ // below don't blow up on non-strings.
+ url = String(url);
+ if (base !== undefined && base !== null) base = String(base);
let full = url;
if (base && !url.includes('://')) {
var bm = base.match(/^(https?:\/\/[^\/\?#]+)(\/[^?#]*)?/);
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 2438a653..ff179818 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -49,6 +49,10 @@ pub struct ObscuraState {
pub intercept_tx: Option<tokio::sync::mpsc::UnboundedSender<InterceptedRequest>>,
pub intercept_counter: u64,
pub intercept_enabled: bool,
+ // Queue of (binding_name, payload) calls made by page JS via the
+ // `op_binding_called` op. Drained by the CDP layer after each dispatch
+ // and emitted as `Runtime.bindingCalled` events.
+ pub pending_binding_calls: Vec<(String, String)>,
}
impl ObscuraState {
@@ -64,6 +68,7 @@ impl ObscuraState {
intercept_tx: None,
intercept_counter: 0,
intercept_enabled: false,
+ pending_binding_calls: Vec::new(),
}
}
}
@@ -770,6 +775,16 @@ async fn op_sleep(#[number] millis: u64) {
tokio::time::sleep(std::time::Duration::from_millis(millis)).await;
}
+// Records a binding call from page JS. The CDP layer drains this queue
+// after every dispatch and emits one `Runtime.bindingCalled` event per
+// entry — that's how puppeteer's `page.exposeFunction` callbacks fire.
+#[op2(fast)]
+fn op_binding_called(state: &OpState, #[string] name: &str, #[string] payload: &str) {
+ let gs = state.borrow::<SharedState>().clone();
+ let mut gs = gs.borrow_mut();
+ gs.pending_binding_calls.push((name.to_string(), payload.to_string()));
+}
+
pub fn build_extension() -> Extension {
Extension {
name: "obscura_dom",
@@ -781,6 +796,7 @@ pub fn build_extension() -> Extension {
op_set_cookie(),
op_navigate(),
op_sleep(),
+ op_binding_called(),
]),
..Default::default()
}
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index f6e49dcd..be035577 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -97,6 +97,10 @@ impl ObscuraJsRuntime {
self.state.borrow_mut().pending_navigation.take()
}
+ pub fn take_pending_binding_calls(&self) -> Vec<(String, String)> {
+ std::mem::take(&mut self.state.borrow_mut().pending_binding_calls)
+ }
+
pub fn set_intercept_tx(&self, tx: tokio::sync::mpsc::UnboundedSender<crate::ops::InterceptedRequest>) {
let mut state = self.state.borrow_mut();
state.intercept_tx = Some(tx);