Skip to content

The headless browser for AI agents and web scraping

fix(forms): honor named child-frame targets

SGavrl955524ab3638
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 3d80031a..0879ee1e 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -7166,6 +7166,96 @@ mod tests {
}
}
+ async fn spawn_form_target_server() -> (
+ String, tokio::sync::mpsc::UnboundedReceiver<(String, String)>,
+ ) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let (sent, requests) = tokio::sync::mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ let sent = sent.clone();
+ tokio::spawn(async move {
+ let mut request = Vec::new();
+ loop {
+ let mut buffer = [0; 2048];
+ let count = socket.read(&mut buffer).await.unwrap();
+ if count == 0 { return; }
+ request.extend_from_slice(&buffer[..count]);
+ let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") else { continue };
+ let headers = String::from_utf8_lossy(&request[..end]);
+ let length = headers.lines().find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse::<usize>().unwrap())
+ }).unwrap_or(0);
+ if request.len() < end + 4 + length { continue; }
+ sent.send((headers.lines().next().unwrap().to_string(),
+ String::from_utf8_lossy(&request[end + 4..]).to_string())).unwrap();
+ break;
+ }
+ let body = "<title>Child response</title><p>submitted</p><script>globalThis.formRan=true</script>";
+ let response = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+ }
+ });
+ (base, requests)
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn form_submission_to_named_iframe_keeps_the_top_document() {
+ let (base, mut requests) = spawn_form_target_server().await;
+ for method in ["GET", "POST"] {
+ for dynamic in [false, true] {
+ let frame = if dynamic { "" } else { "<iframe name='sink'></iframe>" };
+ let html = format!("<title>Top document</title>{frame}<form action='/submit' method='{method}' target='sink'><input name='value' value='hello world'></form>");
+ let mut page = import_map_test_page("named-form", &base, &html);
+ page.evaluate_script(&format!(r#"(() => {{
+ if ({dynamic}) {{ const frame = document.createElement('iframe'); frame.name = 'sink'; document.body.appendChild(frame); }}
+ document.forms[0].submit(); return true;
+ }})()"#)).unwrap();
+ assert!(!page.has_pending_navigation(), "{method}, dynamic={dynamic}: submission targeted the top document");
+ pump_srcdoc_frames(&mut page).await;
+ let expected = if method == "POST" {
+ ("POST /submit HTTP/1.1", "value=hello+world")
+ } else {
+ ("GET /submit?value=hello+world HTTP/1.1", "")
+ };
+ let request = requests.try_recv().expect("form request reached the server");
+ assert_eq!(request, (expected.0.to_string(), expected.1.to_string()));
+ assert_eq!(page.evaluate_script("[document.title, document.querySelector('iframe').contentDocument.title, document.querySelector('iframe').contentWindow.formRan]").unwrap(),
+ serde_json::json!(["Top document", "Child response", true]));
+ }
+ }
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn named_iframe_form_navigation_preserves_targets_and_origin_checks() {
+ let (base, mut requests) = spawn_form_target_server().await;
+ let (other, mut cross_requests) = spawn_form_target_server().await;
+ let mut page = import_map_test_page("named-form-overrides", &base,
+ "<base target='sink'><title>Top document</title><iframe name='sink' srcdoc='initial'></iframe><form action='/submit' method='POST' target='_self'><input name='x' value='1'><button id='send' formtarget='sink'>Send</button></form>");
+ for _ in 0..2 {
+ page.evaluate_script("document.forms[0].requestSubmit(document.getElementById('send'))").unwrap();
+ assert!(!page.has_pending_navigation());
+ pump_srcdoc_frames(&mut page).await;
+ assert_eq!(requests.try_recv().unwrap(), ("POST /submit HTTP/1.1".into(), "x=1".into()));
+ assert_eq!(page.evaluate_script("document.querySelector('iframe').contentDocument.title").unwrap(),
+ serde_json::json!("Child response"));
+ }
+ page.evaluate_script(&format!("document.forms[0].removeAttribute('target'); document.forms[0].action = '{other}/cross'; document.forms[0].submit()" )).unwrap();
+ assert!(!page.has_pending_navigation());
+ pump_srcdoc_frames(&mut page).await;
+ assert_eq!(cross_requests.try_recv().unwrap(), ("POST /cross HTTP/1.1".into(), "x=1".into()));
+ assert_eq!(page.evaluate_script(r#"(() => {
+ const frame = document.querySelector('iframe');
+ let readable = false;
+ try { readable = !!frame.contentWindow.document?.body; } catch (_) {}
+ return [document.title, frame.contentDocument === null, readable];
+ })()"#).unwrap(), serde_json::json!(["Top document", true, false]));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn iframe_srcdoc_loads_parser_and_inserted_documents_in_their_own_realms() {
let mut page = import_map_test_page("srcdoc", "https://parent.test",
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 34d9a84d..37cda11f 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -5167,8 +5167,8 @@ class Element extends Node {
_resetIframeFrame() {
_resetIframeElement(this);
}
- _loadIframeSrc(url) {
- if (this.hasAttribute('srcdoc')) { this._loadIframeSrcdoc(); return; }
+ _loadIframeSrc(url, submission) {
+ if (!submission && this.hasAttribute('srcdoc')) { this._loadIframeSrcdoc(); return; }
if (url === 'about:blank' || !url) { this._resetIframeFrame(); return; }
let fullUrl = url;
if (!url.includes('://')) {
@@ -5176,36 +5176,41 @@ class Element extends Node {
}
// Both the src setter and the parser sweep in __obscura_init reach here, so
// a frame the page assigned before init must not be fetched a second time.
- if (this._iframeLoadingUrl === fullUrl) return;
+ if (!submission && this._iframeLoadingUrl === fullUrl) return;
this._resetIframeFrame();
this._iframeLoadingUrl = fullUrl;
+ // Distinguish repeated form POSTs to the same URL from an older response.
+ const request = this._iframeRequest = {};
const el = this;
- let pageOrigin = '';
- try { pageOrigin = new URL(_domParse('document_url') || 'about:blank').origin; } catch (_) {}
+ const pageOrigin = _realmOrigin();
+ const method = submission?.method || 'GET';
+ const headers = method === 'POST' ? '{"Content-Type":"application/x-www-form-urlencoded"}' : '{}';
+ const body = submission?.body ? new TextEncoder().encode(submission.body) : new Uint8Array(0);
__obscuraCore.ops.op_fetch_url(
- fullUrl, 'GET', '{}', new Uint8Array(0), pageOrigin,
- 'no-cors', 'same-origin', 'Document'
+ fullUrl, method, headers, body, pageOrigin,
+ 'no-cors', submission ? 'include' : 'same-origin', 'Document'
).then(raw => {
- if (el._iframeLoadingUrl !== fullUrl) return;
+ if (el._iframeRequest !== request) return;
const response = JSON.parse(raw);
if (!response.blocked && response.status > 0 && response.status < 400) {
const html = response.body || '';
const loadedUrl = response.url || fullUrl;
el._iframeLoadedUrl = loadedUrl;
el._iframeOpaque = _sandboxOpaqueOrigin;
+ try { el._iframeOpaque ||= new URL(loadedUrl).origin !== pageOrigin; } catch (_) { el._iframeOpaque = true; }
// The host fires load after creating the realm and running its scripts.
const box = el.getBoundingClientRect();
if (el._frameId) globalThis.__obscura_forgetFrame(el._frameId);
el._frameId = __obscuraCore.ops.op_frame_document_ready(
loadedUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150, el._nid);
if (el._frameId) globalThis.__obscura_frameElements[el._frameId] = el;
- el._iframeDoc = new _IframeDocument(html, loadedUrl, el);
- el._iframeWin = new _IframeWindow(el._iframeDoc, loadedUrl);
+ el._iframeDoc = el._iframeOpaque ? null : new _IframeDocument(html, loadedUrl, el);
+ el._iframeWin = el._iframeOpaque ? _remoteWindow(el._frameId) : new _IframeWindow(el._iframeDoc, loadedUrl);
// Bind the window to the realm the host just queued. This is what makes
// posting into the frame reach the frame's own listeners, and makes a
// message coming back out arrive with this window as its `source`.
if (el._frameId) {
- el._iframeWin._frameId = el._frameId;
+ if (!el._iframeOpaque) el._iframeWin._frameId = el._frameId;
globalThis.__obscura_frameWindows[el._frameId] = el._iframeWin;
globalThis.__obscura_frameElements[el._frameId] = el;
return;
@@ -5221,7 +5226,7 @@ class Element extends Node {
// directly bypasses listeners registered via addEventListener.
el.dispatchEvent(new Event('load'));
}).catch(() => {
- if (el._iframeLoadingUrl !== fullUrl) return;
+ if (el._iframeRequest !== request) return;
el._iframeLoadedUrl = fullUrl;
el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);
el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);
@@ -5260,7 +5265,7 @@ class Element extends Node {
if (real?.document) return real.document;
if (this._iframeDoc) {
const pageOrigin = (function(){ try { return new URL(_domParse("document_url")).origin; } catch(e) { return ''; } })();
- if (this.src === '' || this.src === 'about:blank' || this._iframeLoadedUrl === 'about:blank') {
+ if (this._iframeLoadedUrl === 'about:blank') {
return this._iframeDoc;
}
const iframeOrigin = (function(url){ try { return new URL(url).origin; } catch(e) { return ''; } })(this._iframeLoadedUrl);
@@ -5446,11 +5451,25 @@ class Element extends Node {
try { targetUrl = new URL(action, baseUrl).href; } catch(e) { targetUrl = action; }
const encoded = pairs.join('&');
+ if (method !== 'POST') {
+ const sep = targetUrl.includes('?') ? '&' : '?';
+ targetUrl += encoded ? sep + encoded : '';
+ }
+ const owner = this.ownerDocument || document;
+ const target = submitter?.getAttribute('formtarget') ?? this.getAttribute('target') ??
+ owner.querySelector('base[target]')?.getAttribute('target') ?? '';
+ if (target && !['_self', '_parent', '_top', '_blank'].includes(target.toLowerCase())) {
+ for (const frame of owner.getElementsByTagName('iframe')) {
+ if (frame.getAttribute('name') === target && frame.namespaceURI === 'http://www.w3.org/1999/xhtml') {
+ frame._loadIframeSrc(targetUrl, { method: method === 'POST' ? 'POST' : 'GET', body: method === 'POST' ? encoded : '' });
+ return;
+ }
+ }
+ }
if (method === 'POST') {
__obscuraCore.ops.op_navigate(targetUrl, 'POST', encoded);
} else {
- const sep = targetUrl.includes('?') ? '&' : '?';
- __obscuraCore.ops.op_navigate(targetUrl + (encoded ? sep + encoded : ''), 'GET', '');
+ __obscuraCore.ops.op_navigate(targetUrl, 'GET', '');
}
}
reset() {
@@ -15369,6 +15388,7 @@ globalThis.__obscura_liveFrameIds = function () {
// surviving reference keeps the frame's context and DOM tree alive.
globalThis.__obscura_forgetFrame = function (frameId) {
_dom('retire_frame', frameId);
+ _remoteWindows.delete(frameId);
delete globalThis.__obscura_frameElements[frameId];
delete globalThis.__obscura_frameObjects[frameId];
delete globalThis.__obscura_frameWindows[frameId];
@@ -15495,6 +15515,7 @@ function _resetIframeElement(element) {
element._frameId = 0;
element._iframeOpaque = false;
element._iframeLoadingUrl = null;
+ element._iframeRequest = null;
element._iframeLoadedUrl = 'about:blank';
element._iframeDoc = new _IframeDocument(
'<!DOCTYPE html><html><head></head><body></body></html>', 'about:blank', element);