Skip to content

The headless browser for AI agents and web scraping

Merge main and preserve receiver-realm input activation

SGavrl785dc94c5adf
diff --cc crates/obscura-cdp/src/domains/input.rs
index bb7d4ddf,109384c1..656fc0d8
--- a/crates/obscura-cdp/src/domains/input.rs
+++ b/crates/obscura-cdp/src/domains/input.rs
@@@ -227,11 -275,15 +275,15 @@@ pub async fn handle
var cancelled = !clickTarget.dispatchEvent(click);\
if (cancelled) {{\
if (radioStates) {{\
- for (var rr = 0; rr < radioStates.length; rr++) globalThis.__obscura_setFieldValue(radioStates[rr][0], 'checked', radioStates[rr][1]);\
- }} else if (checkable) {{ globalThis.__obscura_setFieldValue(clickTarget, 'checked', oldChecked); clickTarget.indeterminate = oldIndeterminate; }}\
+ for (var rr = 0; rr < radioStates.length; rr++) globalThis.__obscura_setInputChecked(radioStates[rr][0], radioStates[rr][1]);\
+ }} else if (checkable) {{ globalThis.__obscura_setInputChecked(clickTarget, oldChecked); globalThis.__obscura_setInputIndeterminate(clickTarget, oldIndeterminate); }}\
return;\
}}\
+ if ({click_count} === 2) {{\
+ var doubleClick = globalThis.__obscura_markTrusted(new MouseEvent('dblclick', {{bubbles:true,cancelable:true,view:globalThis,clientX:{x},clientY:{y},button:0,buttons:0,detail:2,altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\
+ clickTarget.dispatchEvent(doubleClick);\
+ }}\
- if (checkable && clickTarget.checked !== oldChecked) {{\
+ if (checkable && globalThis.__obscura_inputChecked(clickTarget) !== oldChecked) {{\
try {{ clickTarget.dispatchEvent(globalThis.__obscura_markTrusted(new Event('input', {{bubbles:true}}))); }} catch(e) {{}}\
try {{ clickTarget.dispatchEvent(globalThis.__obscura_markTrusted(new Event('change', {{bubbles:true}}))); }} catch(e) {{}}\
return;\
diff --cc crates/obscura-cdp/tests/input_activation_author_accessors.rs
index 87777d51,00000000..8d233142
mode 100644,000000..100644
--- a/crates/obscura-cdp/tests/input_activation_author_accessors.rs
+++ b/crates/obscura-cdp/tests/input_activation_author_accessors.rs
@@@ -1,186 -1,0 +1,196 @@@
+#![cfg(feature = "render")]
+
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+async fn serve_fixture() -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut buf = [0u8; 2048];
+ let _ = socket.read(&mut buf).await.unwrap();
+ let body = r#"<!doctype html><html><head><style>
- input { display: block; width: 40px; height: 40px; margin: 10px }
++ input, label { display: block; width: 40px; height: 40px; margin: 10px }
+ </style></head><body>
+ <input id="box" type="checkbox">
+ <input id="first" type="radio" name="choice" checked>
+ <input id="second" type="radio" name="choice">
++ <label id="box-label" for="box">Checkbox</label>
++ <label id="second-label" for="second">Radio</label>
+ <script>
+ window.writes = []; window.events = []; window.cancel = false;
+ for (const id of ['box', 'first', 'second']) {
+ const el = document.getElementById(id);
+ if (id === 'box') el.indeterminate = true;
+ for (const key of ['checked', 'indeterminate']) {
+ let proto = Object.getPrototypeOf(el), descriptor;
+ while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, key))) {
+ proto = Object.getPrototypeOf(proto);
+ }
+ Object.defineProperty(el, key, {
+ configurable: true,
+ get() { return descriptor.get.call(this); },
+ set(value) { writes.push(id + ':' + key); descriptor.set.call(this, value); }
+ });
+ }
+ for (const kind of ['click', 'input', 'change']) {
+ el.addEventListener(kind, e => {
+ events.push([id, kind, el.checked, el.indeterminate]);
+ if (kind === 'click' && cancel) e.preventDefault();
+ });
+ }
+ }
+ </script>
+ </body></html>"#;
+ 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()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ });
+ format!("http://{addr}/")
+}
+
+async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, sid: &str) -> Value {
+ let response = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: Some(sid.to_string()),
+ },
+ ctx,
+ )
+ .await;
+ assert!(response.error.is_none(), "CDP {method} failed: {:?}", response.error);
+ response.result.unwrap_or_else(|| json!({}))
+}
+
+async fn evaluate(ctx: &mut CdpContext, id: u64, expression: &str, sid: &str) -> Value {
+ cdp(
+ ctx,
+ id,
+ "Runtime.evaluate",
+ json!({"expression": expression, "returnByValue": true, "awaitPromise": true}),
+ sid,
+ )
+ .await
+}
+
+async fn setup() -> (CdpContext, String) {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve_fixture().await;
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let sid = "author-accessors-session";
+ ctx.sessions.insert(sid.to_string(), page_id);
+ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url, "waitUntil": "load"}), sid).await;
+ (ctx, sid.to_string())
+}
+
+/// Click the centre of `selector` the way a real pointer would.
+async fn click_element(ctx: &mut CdpContext, id: u64, sid: &str, selector: &str) {
+ let rect = evaluate(
+ ctx,
+ id,
+ &format!(
+ "JSON.stringify(document.querySelector('{selector}').getBoundingClientRect().toJSON())"
+ ),
+ sid,
+ )
+ .await;
+ let rect: Value = serde_json::from_str(rect["result"]["value"].as_str().unwrap()).unwrap();
+ let x = rect["x"].as_f64().unwrap() + rect["width"].as_f64().unwrap() / 2.0;
+ let y = rect["y"].as_f64().unwrap() + rect["height"].as_f64().unwrap() / 2.0;
+ for kind in ["mousePressed", "mouseReleased"] {
+ cdp(
+ ctx,
+ id + 1,
+ "Input.dispatchMouseEvent",
+ json!({"type": kind, "x": x, "y": y, "button": "left", "clickCount": 1}),
+ sid,
+ )
+ .await;
+ }
+}
+
+async fn snapshot(ctx: &mut CdpContext, sid: &str) -> Value {
+ let value = evaluate(ctx, 90, r#"JSON.stringify({
+ box: document.getElementById('box').checked,
+ indeterminate: document.getElementById('box').indeterminate,
+ first: document.getElementById('first').checked,
+ second: document.getElementById('second').checked,
+ writes, events
+ })"#, sid).await;
+ serde_json::from_str(value["result"]["value"].as_str().unwrap()).unwrap()
+}
+
+async fn activate(ctx: &mut CdpContext, sid: &str, id: &str, pointer: bool) {
+ if pointer {
+ click_element(ctx, 20, sid, &format!("#{id}")).await;
+ } else {
+ evaluate(ctx, 20, &format!("document.getElementById('{id}').click()"), sid).await;
+ }
+}
+
- async fn verify_activation(pointer: bool) {
++async fn verify_activation(pointer: bool, label: bool) {
+ let (mut ctx, sid) = setup().await;
- activate(&mut ctx, &sid, "box", pointer).await;
++ activate(&mut ctx, &sid, if label { "box-label" } else { "box" }, pointer).await;
+ let s = snapshot(&mut ctx, &sid).await;
+ assert_eq!(s["writes"], json!([]), "native activation must bypass author setters: {s}");
+ assert_eq!(s["box"], true);
+ assert_eq!(s["indeterminate"], false);
+ assert_eq!(s["events"], json!([
+ ["box", "click", true, false], ["box", "input", true, false], ["box", "change", true, false]
+ ]));
+ evaluate(&mut ctx, 30, "events = []", &sid).await;
- activate(&mut ctx, &sid, "second", pointer).await;
++ activate(&mut ctx, &sid, if label { "second-label" } else { "second" }, pointer).await;
+ let s = snapshot(&mut ctx, &sid).await;
+ assert_eq!(s["writes"], json!([]), "radio peers must bypass author setters: {s}");
+ assert_eq!(s["first"], false);
+ assert_eq!(s["second"], true);
+ assert_eq!(s["events"], json!([
+ ["second", "click", true, false], ["second", "input", true, false], ["second", "change", true, false]
+ ]));
+ evaluate(&mut ctx, 40, "document.getElementById('box').checked = false", &sid).await;
+ let s = snapshot(&mut ctx, &sid).await;
+ assert_eq!(s["writes"], json!(["box:checked"]), "script assignment still invokes author setter");
+ assert_eq!(s["box"], false);
+}
+
- async fn verify_cancellation(pointer: bool) {
++async fn verify_cancellation(pointer: bool, label: bool) {
+ let (mut ctx, sid) = setup().await;
+ evaluate(&mut ctx, 10, "cancel = true", &sid).await;
- activate(&mut ctx, &sid, "box", pointer).await;
- activate(&mut ctx, &sid, "second", pointer).await;
++ activate(&mut ctx, &sid, if label { "box-label" } else { "box" }, pointer).await;
++ activate(&mut ctx, &sid, if label { "second-label" } else { "second" }, pointer).await;
+ let s = snapshot(&mut ctx, &sid).await;
+ assert_eq!(s["writes"], json!([]), "activation and rollback bypass author setters: {s}");
+ assert_eq!(s["box"], false);
+ assert_eq!(s["indeterminate"], true);
+ assert_eq!(s["first"], true);
+ assert_eq!(s["second"], false);
+ assert_eq!(s["events"], json!([
+ ["box", "click", true, false], ["second", "click", true, false]
+ ]), "canceled clicks expose pre-activation state but emit no input/change");
+}
+
+#[tokio::test(flavor = "current_thread")]
- async fn native_pointer_activation_bypasses_author_setters() { verify_activation(true).await; }
++async fn native_pointer_activation_bypasses_author_setters() { verify_activation(true, false).await; }
+#[tokio::test(flavor = "current_thread")]
- async fn element_click_activation_bypasses_author_setters() { verify_activation(false).await; }
++async fn element_click_activation_bypasses_author_setters() { verify_activation(false, false).await; }
+#[tokio::test(flavor = "current_thread")]
- async fn native_pointer_cancellation_restores_internal_state() { verify_cancellation(true).await; }
++async fn native_pointer_cancellation_restores_internal_state() { verify_cancellation(true, false).await; }
+#[tokio::test(flavor = "current_thread")]
- async fn element_click_cancellation_restores_internal_state() { verify_cancellation(false).await; }
++async fn element_click_cancellation_restores_internal_state() { verify_cancellation(false, false).await; }
++#[tokio::test(flavor = "current_thread")]
++async fn native_label_activation_bypasses_author_setters() { verify_activation(true, true).await; }
++#[tokio::test(flavor = "current_thread")]
++async fn element_label_activation_bypasses_author_setters() { verify_activation(false, true).await; }
++#[tokio::test(flavor = "current_thread")]
++async fn native_label_cancellation_restores_internal_state() { verify_cancellation(true, true).await; }
++#[tokio::test(flavor = "current_thread")]
++async fn element_label_cancellation_restores_internal_state() { verify_cancellation(false, true).await; }
diff --cc crates/obscura-cdp/tests/integration.rs
index 00000000,1d522a94..e92712d5
mode 000000,100644..100644
--- a/crates/obscura-cdp/tests/integration.rs
+++ b/crates/obscura-cdp/tests/integration.rs
@@@ -1,0 -1,59 +1,60 @@@
+ // One link of the browser engine. Nextest still starts a process per test.
+ macro_rules! integration_tests {
+ ($($module:ident),* $(,)?) => {
+ $(mod $module;)*
+
+ #[test]
+ fn every_integration_file_is_registered() {
+ use std::collections::BTreeSet;
+ let registered: BTreeSet<String> = [$(stringify!($module).to_owned(),)*]
+ .into_iter().collect();
+ let files: BTreeSet<String> = std::fs::read_dir(
+ concat!(env!("CARGO_MANIFEST_DIR"), "/tests"),
+ ).unwrap().map(|entry| entry.unwrap().path())
+ .filter(|path| path.extension().is_some_and(|ext| ext == "rs"))
+ .map(|path| path.file_stem().unwrap().to_str().unwrap().to_owned())
+ .filter(|name| name != "integration")
+ .collect();
+ assert_eq!(registered, files, "register new test files in integration_tests!");
+ }
+ };
+ }
+
+ integration_tests!(
+ accept_thread_survives_silent_connections,
+ accessibility_names,
+ backspace_surrogate,
+ binding_called_session,
+ cdp_click_submit_parity,
+ child_frame_tree,
+ concurrent_connections_heavy_page,
+ concurrent_navigations,
+ concurrent_navigations_with_fetch,
+ concurrent_page_isolation,
+ control_plane_unblocked,
+ document_write_lifecycle,
+ dynamic_script_onload_fires,
+ dynamic_stylesheet_onload_fires,
+ execution_context_ownership,
+ execution_context_pruned_on_navigation,
+ file_navigation_gate,
+ form_submit_method_bypasses_listener,
+ iframe_event_dispatch,
++ input_activation_author_accessors,
+ input_key_event_escaping,
+ input_mouse_event_parity,
+ input_mouse_label_activation,
+ js_fetch_emits_network_events,
+ max_connections_cap,
+ nodefilter_constants,
+ page_frame_contract,
+ runtime_by_value_undefined,
+ runtime_console_events,
+ runtime_get_properties_objectid_escaping,
+ runtime_primitives,
+ scroll_event_on_assignment,
+ structured_clone_crypto_parity,
+ textarea_enter_selection,
+ treewalker_document_order,
+ window_conformance_parity,
+ );
diff --cc crates/obscura-js/js/bootstrap.js
index 148d6bff,2d47383f..ba49870b
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@@ -3058,7 -3090,7 +3118,9 @@@ globalThis.__obscura_interactiveHost =
// Frozen so page script can neither replace the helpers to suppress or fake
// label activation, nor delete them and make later clicks throw.
for (const _name of ['__obscura_activateLabel', '__obscura_isDisabled',
-- '__obscura_labeledControl', '__obscura_interactiveHost']) {
++ '__obscura_labeledControl', '__obscura_interactiveHost',
++ '__obscura_inputChecked', '__obscura_setInputChecked',
++ '__obscura_inputIndeterminate', '__obscura_setInputIndeterminate']) {
Object.defineProperty(globalThis, _name, { writable: false, configurable: false });
}
@@@ -3924,6 -4022,6 +4052,12 @@@ class Element extends Node
// private token so the forwarded events stay trusted. Read from arguments
// to keep click.length at 0, as in a real browser.
const _trusted = arguments[0] === _TRUSTED_ACTIVATION;
++ // A borrowed method must activate in the receiver's realm: node ids and
++ // private checkedness are local to each document.
++ if (_cache.get(this._nid) !== this) {
++ const activate = _documentRealmMember(this, 'activateElement');
++ if (activate) return activate.call(this, _trusted);
++ }
// Pre-click activation steps (HTML spec): a checkbox/radio flips BEFORE the
// click event dispatches, so listeners observe the new state, and the change
// is reverted if the event is cancelled. This mirrors the CDP mouse path in
@@@ -15649,6 -16752,13 +16781,18 @@@ if (typeof ShadowRoot !== 'undefined' &
};
}
-// Capture late-defined document members too, before page code can replace them.
-const _documentMembers = Object.freeze(Object.fromEntries(
- ['URL', 'defaultView', 'readyState', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'close', 'elementFromPoint'].map(name => {
++// Capture late-defined members too, before page code can replace them.
++const _nativeElementClick = Element.prototype.click;
++const _documentMembers = Object.freeze(Object.fromEntries([
++ ...['URL', 'defaultView', 'readyState', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'close', 'elementFromPoint'].map(name => {
+ const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, name);
+ return [name, descriptor.value || descriptor.get];
- })));
++ }),
++ ['activateElement', function(trusted) {
++ return _nativeElementClick.call(this, trusted ? _TRUSTED_ACTIVATION : undefined);
++ }],
++]));
+
globalThis.__obscura_init = function() {
// The host sets __obscura_frameId on a frame realm before calling this.
_realmFrameId = globalThis.__obscura_frameId >>> 0;
diff --cc crates/obscura-js/src/runtime.rs
index 0346a104,63b62b18..b6fbbbe2
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@@ -4749,40 -5040,163 +5040,193 @@@ mod tests
assert_eq!(
rt.evaluate(
r#"(() => {
- const iframe = document.createElement("iframe");
+ const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const child = iframe.contentWindow;
- const names = [
- "Object", "Function", "Error", "Promise", "Proxy",
- "XMLHttpRequest", "Worker", "Blob", "FormData",
- "WebSocket", "MutationObserver",
- ];
- return {
- types: names.map(name => typeof child[name]),
- separate: [
- child.Object !== Object,
- child.Promise !== Promise,
- child.XMLHttpRequest !== XMLHttpRequest,
- child.Math !== Math,
- ],
- constructible: [
- new child.Object() instanceof child.Object,
- new child.Promise(resolve => resolve()) instanceof child.Promise,
- new child.XMLHttpRequest() instanceof child.XMLHttpRequest,
- new child.Blob([]) instanceof child.Blob,
- new child.FormData() instanceof child.FormData,
- new child.MutationObserver(() => {}) instanceof child.MutationObserver,
- ],
- utilities: [
- child.Object.keys({ first: 1 })[0] === "first",
- child.Array.isArray([]),
- child.Promise.resolve(1) instanceof child.Promise,
- child.Function("return 7")() === 7,
- Object.getOwnPropertyNames(child).includes("XMLHttpRequest"),
- child.globalThis === child,
- ],
- };
+ const globalMatches = child.eval('globalThis') === child;
+ const constructorMatches = child.eval('Array') === child.Array;
+ child.eval('globalThis.__initialFrameSentinel = 123');
+ return [globalMatches, constructorMatches,
+ child.__initialFrameSentinel === 123,
+ globalThis.__initialFrameSentinel === undefined];
+ })()"#,
+ ).unwrap(),
+ serde_json::json!([true, true, true, true])
+ );
+ }
+
++ #[test]
++ fn borrowed_input_activation_uses_the_receiver_realm() {
++ let mut rt = setup_runtime("<input id='parent' type='checkbox'><iframe></iframe>");
++ assert_eq!(rt.evaluate(r#"(() => {
++ const child = document.querySelector('iframe').contentDocument;
++ child.body.innerHTML = '<input id="control" type="checkbox">';
++ const input = child.getElementById('control');
++ const events = [];
++ input.indeterminate = true;
++ input.addEventListener('click', event => {
++ events.push(['click', input.checked, input.indeterminate]);
++ if (cancel) event.preventDefault();
++ });
++ for (const type of ['input', 'change']) {
++ input.addEventListener(type, () => events.push([type, input.checked, input.indeterminate]));
++ }
++ let cancel = true;
++ HTMLElement.prototype.click.call(input);
++ const cancelled = [input.checked, input.indeterminate,
++ document.getElementById('parent').checked, events.splice(0)];
++ cancel = false;
++ HTMLElement.prototype.click.call(input);
++ return [cancelled, [input.checked, input.indeterminate,
++ document.getElementById('parent').checked, events]];
++ })()"#).unwrap(), serde_json::json!([
++ [false, true, false, [["click", true, false]]],
++ [true, false, false, [["click", true, false], ["input", true, false], ["change", true, false]]]
++ ]));
++ }
++
+ #[test]
+ fn document_open_does_not_use_overridden_head_or_body_getters() {
+ let mut rt = setup_runtime(
+ "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const childDocument = iframe.contentDocument;
+ Object.defineProperties(childDocument, {
+ head: { get: () => document.head },
+ body: { get: () => document.body },
+ });
+ Document.prototype.open.call(childDocument);
+ return [document.body.textContent, document.baseURI];
+ })()"#).unwrap(), serde_json::json!(["parent", "https://parent.example/"]));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn synchronous_iframe_geometry_uses_the_owning_document() {
+ let mut rt = setup_runtime(
+ "<html><head><style>body{margin:4px}#parent{width:45px;height:30px}</style></head><body><div id='parent'></div></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const d = iframe.contentDocument;
+ d.body.innerHTML = '<style>body{margin:8px}div{width:100px;height:20px}</style><div id="child"></div>';
+ const element = d.getElementById('child');
+ const range = d.createRange(); range.selectNode(element);
+ return [[...element.getClientRects()].map(r => [r.width, r.height, r.bottom]),
+ [...range.getClientRects()].map(r => r.bottom),
+ [element.clientWidth, element.clientHeight, element.offsetWidth, element.offsetHeight],
+ d.elementFromPoint(10, 10) === element,
+ document.getElementById('parent').getBoundingClientRect().width];
+ })()"#).unwrap(), serde_json::json!([
+ [[100, 20, 28]], [28], [100, 20, 100, 20], true, 45
+ ]));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn borrowed_document_hit_testing_uses_the_receiver_realm() {
+ let mut rt = setup_runtime(
+ "<style>body{margin:4px}#parent{width:45px;height:30px}</style><div id='parent'></div>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const d = iframe.contentDocument;
+ d.body.innerHTML = '<style>body{margin:8px}div{width:100px;height:20px}</style><div id="child"></div>';
+ const child = d.getElementById('child'), parent = document.getElementById('parent');
+ const foreign = iframe.contentWindow.Document.prototype;
+ return [document.elementFromPoint(10, 10) === parent,
+ d.elementFromPoint(10, 10) === child,
+ Document.prototype.elementFromPoint.call(d, 10, 10) === child,
+ foreign.elementFromPoint.call(document, 10, 10) === parent,
+ Document.prototype.elementFromPoint.call(d, 400, 10) === null,
+ foreign.elementFromPoint.call(document, 400, 10) === document.body,
+ Document.prototype.elementsFromPoint.call(d, 10, 10)[0] === child,
+ foreign.elementsFromPoint.call(document, 10, 10)[0] === parent];
+ })()"#).unwrap(), serde_json::json!([true, true, true, true, true, true, true, true]));
+ }
+
+ #[cfg(feature = "render")]
+ #[test]
+ fn computed_style_on_a_foreign_frame_element_tracks_its_document() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const d = iframe.contentDocument;
+ d.body.innerHTML = '<style>#child{width:100px;height:20px;color:rgb(12,34,56)}</style><div id="child"></div>';
+ const element = d.getElementById('child');
+ const style = getComputedStyle(element);
+ const before = [style.width, style.color];
+ element.style.width = '120px';
+ element.style.color = 'rgb(78,90,12)';
+ return [before, [style.width, style.color], getComputedStyle(element).color];
+ })()"#).unwrap(), serde_json::json!([
+ ["100px", "rgb(12, 34, 56)"], ["120px", "rgb(78, 90, 12)"], "rgb(78, 90, 12)"
+ ]));
+ }
+
+ #[test]
+ fn borrowed_document_methods_keep_the_receiver_realm_after_prototype_remap() {
+ let mut rt = setup_runtime(
+ "<html><head><base href='https://parent.example/'></head><body>parent</body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const childDocument = child.document;
+ Object.setPrototypeOf(childDocument, Document.prototype);
+ const initialUrl = childDocument.URL;
+ const separateBody = childDocument.querySelector('body') !== document.body;
+ Document.prototype.open.call(childDocument);
+ return [document.body.textContent, document.baseURI, document.readyState,
+ separateBody, initialUrl];
+ })()"#).unwrap(), serde_json::json!([
+ "parent", "https://parent.example/", "complete", true, "about:blank"
+ ]));
+ }
+
+ #[test]
+ fn iframe_content_window_exposes_realm_globals() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+
+ assert_eq!(
+ rt.evaluate(
+ r#"(() => {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const child = iframe.contentWindow;
+ const names = [
+ "Object", "Function", "Error", "Promise", "Proxy",
+ "XMLHttpRequest", "Worker", "Blob", "FormData",
+ "WebSocket", "MutationObserver",
+ ];
+ return {
+ types: names.map(name => typeof child[name]),
+ separate: [
+ child.Object !== Object,
+ child.Promise !== Promise,
+ child.XMLHttpRequest !== XMLHttpRequest,
+ child.Math !== Math,
+ ],
+ constructible: [
+ new child.Object() instanceof child.Object,
+ new child.Promise(resolve => resolve()) instanceof child.Promise,
+ new child.XMLHttpRequest() instanceof child.XMLHttpRequest,
+ new child.Blob([]) instanceof child.Blob,
+ new child.FormData() instanceof child.FormData,
+ new child.MutationObserver(() => {}) instanceof child.MutationObserver,
+ ],
+ utilities: [
+ child.Object.keys({ first: 1 })[0] === "first",
+ child.Array.isArray([]),
+ child.Promise.resolve(1) instanceof child.Promise,
+ child.Function("return 7")() === 7,
+ Object.getOwnPropertyNames(child).includes("XMLHttpRequest"),
+ child.globalThis === child,
+ ],
+ };
})()"#,
)
.unwrap(),