The headless browser for AI agents and web scraping
feat(js): deliver postMessage between a page and its frames
xrip3db9c60dc5d3
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 345e6f10..7f9e1809 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1038,6 +1038,57 @@ impl Page {true}+ /// Hands each queued `postMessage` to the realm it was addressed to.+ ///+ /// Reports whether anything was delivered, because a message usually causes+ /// a reply: a widget posts its result, the page answers, and the exchange+ /// only finishes if the caller settles and drains again.+ fn deliver_frame_messages(&mut self) -> bool {+ let pending = match self.js.as_ref() {+ Some(js) => js.take_pending_frame_messages(),+ None => return false,+ };+ if pending.is_empty() {+ return false;+ }++ for message in pending {+ let escaped_data = serde_json::to_string(&message.data_json).unwrap_or_default();+ let escaped_origin = serde_json::to_string(&message.origin).unwrap_or_default();+ if message.target_frame_id == 0 {+ let Some(js) = self.js.as_mut() else { continue };+ let script = format!(+ "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {});",+ message.source_frame_id,+ );+ if let Err(error) = js.execute_script("<frame-message>", &script) {+ tracing::debug!("message to the page failed: {error}");+ }+ continue;+ }++ let Some(index) = self+ .frames+ .iter()+ .position(|frame| frame.frame_id() == message.target_frame_id)+ else {+ // The frame was torn down between the send and the drain.+ tracing::debug!("message for frame {} which is gone", message.target_frame_id);+ continue;+ };+ let Some(js) = self.js.as_mut() else { continue };+ if let Err(error) = self.frames[index].deliver_message(+ js,+ &message.data_json,+ &message.origin,+ message.source_frame_id,+ ) {+ tracing::debug!("message to frame {} failed: {error}", message.target_frame_id);+ }+ }+ true+ }+/// URLs of the page's live child frames, in creation order.pub fn frame_urls(&self) -> Vec<String> {self.frames@@ -2408,7 +2459,11 @@ impl Page {let _ = js.run_event_loop_until_quiescent(remaining, 150).await;}}- if !self.attach_pending_frames().await {+ let attached = self.attach_pending_frames().await;+ // A message usually causes a reply, so keep going while either the+ // frame tree or the conversation is still moving.+ let delivered = self.deliver_frame_messages();+ if !attached && !delivered {break;}}@@ -2449,6 +2504,7 @@ impl Page {// Their document scripts still run; only their own deferred work is// left for a later settle.self.attach_pending_frames().await;+ self.deliver_frame_messages();}/// Advance one wake-driven browser task for a continuously owned page.diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 2a7cb706..551e7655 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -3845,6 +3845,11 @@ class Element extends Node {fullUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150);el._iframeDoc = new _IframeDocument(html, fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);+ // 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`.+ el._iframeWin._frameId = el._frameId;+ globalThis.__obscura_frameWindows[el._frameId] = el._iframeWin;} else {el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);@@ -11616,6 +11621,112 @@ const _iframeWindowProxyHandler = {},};+// Cross-realm messaging.+//+// A realm cannot reach another realm's context on its own, so postMessage is+// handed to the host, which delivers it into the target realm. These are+// declared rather than assigned by the host so the snapshot-time hide list+// picks them up; a global added later would stay enumerable on `window`.+globalThis.__obscura_frameId = 0; // 0 is the page's own realm+globalThis.__obscura_parentFrameId = 0;+globalThis.__obscura_frameWindows = Object.create(null); // frame id -> its window++function _realmOrigin() {+ try { return new URL(_domParse('document_url')).origin; } catch (_) { return 'null'; }+}++function _sendRealmMessage(targetFrameId, data) {+ let json;+ // Structured clone cannot cross realms here. JSON carries what postMessage is+ // actually used for; anything else throws the same DataCloneError a browser+ // throws for an unclonable value, rather than arriving silently as null.+ try {+ json = JSON.stringify({ v: data === undefined ? null : data });+ } catch (_) {+ throw new DOMException('The object could not be cloned.', 'DataCloneError');+ }+ if (json === undefined) json = '{"v":null}';+ Deno.core.ops.op_post_frame_message(+ targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), json);+}++// The host calls this inside the target realm.+globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId) {+ let data = null;+ try { data = JSON.parse(dataJson).v; } catch (_) {}+ // Who to reply to: the frame above, or one of the frames below.+ const source = (globalThis.__obscura_frameId !== 0+ && sourceFrameId === globalThis.__obscura_parentFrameId)+ ? globalThis.parent+ : (globalThis.__obscura_frameWindows[sourceFrameId] || null);+ try {+ // Trusted, because the user agent delivers this event: the sender called+ // postMessage, it did not dispatch this. Real embedders check the flag and+ // drop anything untrusted, so an untrusted event is not merely suspicious,+ // it is silently discarded and the widget waits forever.+ globalThis.dispatchEvent(globalThis.__obscura_markTrusted(+ new MessageEvent('message', { data, origin, source })));+ } catch (error) {+ console.error('message listener failed:', error && error.message || error);+ }+};++// A window in another browsing context, as seen from this one.+//+// Only the cross-origin surface is exposed: reaching synchronously into another+// realm's DOM is not something this engine does, and a browser forbids it+// across origins anyway. Widgets use postMessage regardless, which is what it+// is for.+class _RemoteWindow {+ constructor(frameId) {+ Object.defineProperty(this, '_frameId', { value: frameId, enumerable: false });+ }+ postMessage(data, _targetOrigin, _transfer) { _sendRealmMessage(this._frameId, data); }+ get self() { return this; }+ get window() { return this; }+ get frames() { return this; }+ get parent() { return this; }+ get top() { return this; }+ get opener() { return null; }+ get closed() { return false; }+ get length() { return 0; }+ focus() {}+ blur() {}+ close() {}+}+_markNative(_RemoteWindow.prototype.postMessage);++const _remoteWindows = new Map();+function _remoteWindow(frameId) {+ let win = _remoteWindows.get(frameId);+ if (!win) {+ win = new _RemoteWindow(frameId);+ _remoteWindows.set(frameId, win);+ }+ return win;+}++// Installs `parent` and `top` for a framed document. Called from+// __obscura_init, before any of the document's own scripts run: `parent ===+// window` is how a document decides it is top-level, and one script taking+// that branch wrongly is enough to change everything after it.+function _installFramingRelationships() {+ if (!globalThis.__obscura_frameId) return; // the page really is the top+ for (const [name, frameId] of [+ ['parent', globalThis.__obscura_parentFrameId],+ ['top', 0], // the top browsing context is always the page's realm+ ]) {+ try {+ Object.defineProperty(globalThis, name, {+ value: _remoteWindow(frameId),+ writable: false,+ enumerable: true,+ configurable: true,+ });+ } catch (_) {}+ }+}+class _IframeWindow {constructor(doc, url) {this.document = doc;@@ -11659,15 +11770,13 @@ class _IframeWindow {return proxy;}- postMessage(data, origin) {- const event = new MessageEvent('message', {- data: data,- origin: this.location.origin,- source: this,- });- Promise.resolve().then(() => {- globalThis.dispatchEvent?.(event);- });+ postMessage(data, _targetOrigin, _transfer) {+ // Into the frame's own realm, through the host. This used to dispatch the+ // event on the *parent's* window, so a page could never actually talk to+ // the document inside its iframe. A frame that has not loaded yet has no+ // browsing context to receive anything.+ if (!this._frameId) return;+ _sendRealmMessage(this._frameId, data);}setTimeout(fn, ms) { return globalThis.setTimeout(fn, ms); }@@ -12661,7 +12770,30 @@ globalThis.prompt = function() { return null; }; _markNative(globalThis.prompt);globalThis.open = function() { return null; }; _markNative(globalThis.open);globalThis.close = function() {}; _markNative(globalThis.close);globalThis.stop = function() {}; _markNative(globalThis.stop);-globalThis.postMessage = function() {}; _markNative(globalThis.postMessage);+// `window.postMessage` targets this same window. It was a no-op, so a page+// that posted to itself and waited for the `message` event waited forever.+// Same realm, so this needs no host round trip; it is queued as a task because+// postMessage never delivers synchronously.+globalThis.postMessage = function(data, _targetOrigin, _transfer) {+ let clone = data;+ // Match the cross-realm path: a value postMessage cannot carry is rejected+ // at the call, not delivered as something else.+ try {+ clone = JSON.parse(JSON.stringify({ v: data === undefined ? null : data })).v;+ } catch (_) {+ throw new DOMException('The object could not be cloned.', 'DataCloneError');+ }+ const origin = _realmOrigin();+ setTimeout(() => {+ try {+ globalThis.dispatchEvent(globalThis.__obscura_markTrusted(+ new MessageEvent('message', { data: clone, origin, source: globalThis })));+ } catch (error) {+ console.error('message listener failed:', error && error.message || error);+ }+ }, 0);+};+_markNative(globalThis.postMessage);globalThis.requestIdleCallback = globalThis.requestIdleCallback || function(cb) { return setTimeout(cb, 0); };globalThis.cancelIdleCallback = globalThis.cancelIdleCallback || function(id) { clearTimeout(id); };if (typeof ReadableStream === 'undefined') {@@ -14095,6 +14227,11 @@ globalThis.__obscura_init = function() {// version from navigator.userAgent and read the platform from the page// globals, so every stealth surface agrees without a per-mode override.+ // Before any of this document's own scripts run: `parent === window` is how+ // a document decides it is top-level, and one script taking that branch+ // wrongly changes everything after it.+ _installFramingRelationships();+// A parser-created <iframe src> never went through the src setter, so// nothing had started its load and the frame stayed empty (issue #600).// This also runs inside a frame realm, so a frame nested in a frame loadsdiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex e4592e1c..e94d58e6 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -124,6 +124,24 @@ impl FrameRealm {)}+ /// Delivers a `postMessage` that another realm sent to this one.+ pub fn deliver_message(+ &self,+ parent: &mut ObscuraJsRuntime,+ data_json: &str,+ origin: &str,+ source_frame_id: u32,+ ) -> Result<(), String> {+ self.execute_script(+ parent,+ &format!(+ "globalThis.__obscura_deliverMessage({}, {}, {source_frame_id});",+ encode_json_argument(data_json),+ encode_json_argument(origin),+ ),+ )+ }+pub fn frame_id(&self) -> u32 {self.frame_id}@@ -312,6 +330,12 @@ impl DocumentScript {}}+/// Embeds a string in JavaScript source as a literal, so a payload holding+/// quotes or newlines cannot end the literal and be read as code.+fn encode_json_argument(value: &str) -> String {+ serde_json::to_string(value).unwrap_or_else(|_| "\"\"".to_string())+}+/// Serializes an origin the way `location.origin` does, using `"null"` for/// schemes that have no tuple origin.fn origin_of(url: &str) -> String {@@ -713,6 +737,109 @@ mod tests {);}+ /// A frame posting to `parent` must reach the page, arrive trusted, and+ /// carry the frame's origin. Turnstile and every widget like it drop an+ /// untrusted message silently, so an untrusted delivery is not a cosmetic+ /// difference, it is the widget hanging forever.+ #[test]+ fn a_frame_posts_to_its_parent_as_a_trusted_message() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ parent+ .execute_script(+ "p",+ "globalThis.got = [];\+ addEventListener('message', (e) => globalThis.got.push(\+ [e.data, e.origin, e.isTrusted]));",+ )+ .unwrap();+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/f",+ "<html><body></body></html>",+ )+ .expect("frame realm");++ frame+ .execute_script(&mut parent, "parent.postMessage({token: 'ok'}, '*');")+ .unwrap();+ // The host is the transport, exactly as `Page` does between turns.+ let queued = parent.take_pending_frame_messages();+ assert_eq!(queued.len(), 1);+ assert_eq!(queued[0].target_frame_id, 0);+ assert_eq!(queued[0].source_frame_id, 1);+ let script = format!(+ "globalThis.__obscura_deliverMessage({}, {}, {});",+ serde_json::to_string(&queued[0].data_json).unwrap(),+ serde_json::to_string(&queued[0].origin).unwrap(),+ queued[0].source_frame_id,+ );+ parent.execute_script("<frame-message>", &script).unwrap();++ assert_eq!(+ parent.evaluate("globalThis.got").unwrap(),+ serde_json::json!([[{"token": "ok"}, "https://child.example", true]]),+ );+ }++ /// `parent === window` is how a document decides it is top-level, so a+ /// framed realm must not see itself as the top.+ #[test]+ fn a_framed_realm_does_not_look_top_level() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 2,+ 0,+ "https://child.example/f",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ assert_eq!(+ frame+ .evaluate(&mut parent, "[parent === window, top === window]")+ .unwrap(),+ serde_json::json!([false, false]),+ );+ // The page itself really is the top and must still say so.+ assert_eq!(+ parent.evaluate("[parent === window, top === window]").unwrap(),+ serde_json::json!([true, true]),+ );+ }++ /// Script can post in a synchronous loop while the host only drains between+ /// event loop turns, and this queue is on the process heap rather than+ /// V8's, where the heap-limit guard would never see it.+ #[test]+ fn a_flood_of_messages_cannot_grow_the_queue_without_bound() {+ std::env::set_var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES", "64");+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/f",+ "<html><body></body></html>",+ )+ .expect("frame realm");++ frame+ .execute_script(+ &mut parent,+ "for (let i = 0; i < 5000; i++) parent.postMessage(i, '*');",+ )+ .unwrap();++ let queued = parent.take_pending_frame_messages();+ assert_eq!(queued.len(), 64, "the queue was not capped");+ // The messages kept are the earliest, which is the half of a handshake+ // that matters.+ assert_eq!(queued[0].data_json, r#"{"v":0}"#);+ std::env::remove_var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES");+ }+#[test]fn opaque_origin_frames_are_never_same_origin() {let mut parent = page("https://parent.example/", "<html><body></body></html>");diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 9857058f..70e65998 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -148,6 +148,15 @@ pub struct ObscuraState {pub frame_id_counter: u32,/// Which frame this state belongs to; 0 is the page's own realm.pub frame_id: u32,+ // postMessage traffic between realms, waiting to be delivered. A realm+ // cannot reach another realm's context on its own, so the message is queued+ // here and the Page dispatches it, the same way frames themselves are+ // built. Queued on the *page's* state whichever realm sent it, so one drain+ // sees the traffic of the whole tree.+ pub pending_frame_messages: Vec<PendingFrameMessage>,+ /// Bytes of payload currently queued above, tracked rather than summed so+ /// the cap costs nothing per message.+ pub pending_frame_message_bytes: usize,/// Requests initiated by this runtime only. Browser contexts share their/// transport client across pages, so the client's aggregate counter cannot/// be used as a page-readiness signal.@@ -248,6 +257,21 @@ pub struct PendingFrame {pub parent_frame_id: u32,}+/// One `postMessage` in flight between two realms.+pub struct PendingFrameMessage {+ /// Where it is going. 0 is the page's realm.+ pub target_frame_id: u32,+ /// Where it came from, so the receiver can reply through `event.source`.+ pub source_frame_id: u32,+ /// The sender's origin, for `event.origin`.+ pub origin: String,+ /// The payload, JSON encoded. Structured clone is not available across+ /// realms here, and JSON covers what postMessage is used for in practice:+ /// a widget reporting a result. Anything it cannot encode is rejected by+ /// the sender rather than silently arriving as null.+ pub data_json: String,+}+impl ObscuraState {pub fn new() -> Self {ObscuraState {@@ -275,6 +299,8 @@ impl ObscuraState {pending_frames: Vec::new(),frame_id_counter: 0,frame_id: 0,+ pending_frame_messages: Vec::new(),+ pending_frame_message_bytes: 0,page_in_flight: Arc::new(std::sync::atomic::AtomicU32::new(0)),activity_generation: 0,document_generation: 0,@@ -3380,6 +3406,63 @@ fn op_navigate(gs.pending_navigation = Some((url.to_string(), method.to_string(), body.to_string()));}+fn frame_message_queue_entry_limit() -> usize {+ std::env::var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(4096)+}++fn frame_message_queue_byte_limit() -> usize {+ std::env::var("OBSCURA_FRAME_MESSAGE_QUEUE_BYTES")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(8 * 1024 * 1024)+}++// Queues one postMessage for another realm. Always on the page's state, never+// the caller's: the Page drains a single queue, and a message sent by a nested+// frame would otherwise sit in that frame's own state and never be looked at.+//+// The queue is capped. Script can post in a synchronous loop while the host+// only drains between event loop turns, and this buffer lives on the process+// heap rather than V8's, so an unbounded queue would let a page grow memory+// without bound in the one place the heap-limit guard cannot see. Over the cap+// the newest message is dropped, keeping the earlier traffic that a widget+// handshake actually depends on.+#[op2(fast)]+fn op_post_frame_message(+ state: &OpState,+ target_frame_id: u32,+ source_frame_id: u32,+ #[string] origin: &str,+ #[string] data_json: &str,+) {+ let gs = state.borrow::<SharedState>().clone();+ let mut gs = gs.borrow_mut();+ let over_entries = gs.pending_frame_messages.len() >= frame_message_queue_entry_limit();+ let over_bytes = gs+ .pending_frame_message_bytes+ .saturating_add(data_json.len())+ > frame_message_queue_byte_limit();+ if over_entries || over_bytes {+ tracing::warn!(+ "dropping a postMessage for frame {}: {} already queued, {} bytes",+ target_frame_id,+ gs.pending_frame_messages.len(),+ gs.pending_frame_message_bytes,+ );+ return;+ }+ gs.pending_frame_message_bytes = gs.pending_frame_message_bytes.saturating_add(data_json.len());+ gs.pending_frame_messages.push(PendingFrameMessage {+ target_frame_id,+ source_frame_id,+ origin: origin.to_string(),+ data_json: data_json.to_string(),+ });+}+/// Resolves after `millis`, as the timer source for child frame realms.////// deno_core's own timer queue is not usable from a frame: `op_timer_queue`@@ -4146,6 +4229,7 @@ pub fn build_extension() -> Extension {op_set_cookie(),op_navigate(),op_frame_document_ready(),+ op_post_frame_message(),op_sleep(),op_async_runtime_available(),op_posted_task(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex c2385750..5a3334c3 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -606,6 +606,13 @@ impl ObscuraJsRuntime {std::mem::take(&mut self.state.borrow_mut().pending_frames)}+ /// postMessage traffic waiting to be delivered to another realm.+ pub fn take_pending_frame_messages(&self) -> Vec<crate::ops::PendingFrameMessage> {+ let mut state = self.state.borrow_mut();+ state.pending_frame_message_bytes = 0;+ std::mem::take(&mut state.pending_frame_messages)+ }+/// Restore the configured V8 heap limit after the emergency headroom has/// allowed a terminated allocation to unwind. The callback is then armed/// again so a second hostile script cannot grow the isolate without bound.diff --git a/crates/obscura/tests/child_frame_scripts.rs b/crates/obscura/tests/child_frame_scripts.rsindex 2b500298..acd0e75f 100644--- a/crates/obscura/tests/child_frame_scripts.rs+++ b/crates/obscura/tests/child_frame_scripts.rs@@ -27,6 +27,32 @@ const CHILD_HTML: &str = r#"<!doctype html><html><head><title>BEFORE</title></he</script></body></html>"#;+/// The reporter's original pair: the child reports to its parent over+/// postMessage, which is how every embedded widget returns a result.+const MESSAGING_PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></head><body>+<script>+ window.__res = {parentGot: [], trusted: [], fromChildWindow: []};+ window.addEventListener('message', function (e) {+ window.__res.parentGot.push(String(e.data));+ window.__res.trusted.push(e.isTrusted === true);+ window.__res.fromChildWindow.push(e.source === document.querySelector('iframe').contentWindow);+ });+ var f = document.createElement('iframe');+ f.src = '/child-messaging.html';+ document.body.appendChild(f);+</script>+</body></html>"#;++const MESSAGING_CHILD_HTML: &str = r#"<!doctype html><html><body>+<script>+ try { parent.postMessage("FROM-CHILD", "*"); }+ catch (e) { document.title = "POST-THREW:" + e.message; }+ window.addEventListener('message', function (e) {+ window.__heard = String(e.data) + ':' + (e.isTrusted === true);+ });+</script>+</body></html>"#;+/// Minimal HTTP/1.1 server serving the parent document at `/` and the child at/// `/child.html`.fn spawn_server(parent_html: &'static str) -> String {@@ -42,6 +68,8 @@ fn spawn_server(parent_html: &'static str) -> String {let read = stream.read(&mut buf).unwrap_or(0);let body = if buf[..read].starts_with(b"GET /child.html ") {CHILD_HTML+ } else if buf[..read].starts_with(b"GET /child-messaging.html ") {+ MESSAGING_CHILD_HTML} else {parent_html};@@ -91,6 +119,84 @@ async fn a_child_frame_runs_its_own_script() {assert_eq!(page.evaluate("window.__ran"), serde_json::Value::Null);}+/// The whole point of a child frame having a scripting context: it can report+/// its result back out. This is the reporter's `parentGot` assertion.+#[tokio::test]+async fn a_child_frame_reaches_its_parent_with_post_message() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(MESSAGING_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;++ assert_eq!(+ page.evaluate("window.__res.parentGot"),+ serde_json::json!(["FROM-CHILD"]),+ "the child's message never reached the parent"+ );+ // A widget gates on isTrusted and drops anything else without a word.+ assert_eq!(+ page.evaluate("window.__res.trusted"),+ serde_json::json!([true]),+ );+ // And it replies through event.source, so that has to be the frame's window.+ assert_eq!(+ page.evaluate("window.__res.fromChildWindow"),+ serde_json::json!([true]),+ );+}++/// The other direction: a page talking into its frame.+#[tokio::test]+async fn a_parent_reaches_its_child_with_post_message() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(MESSAGING_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;++ page.evaluate("document.querySelector('iframe').contentWindow.postMessage('TO-CHILD', '*')");+ page.settle(1000).await;++ assert_eq!(+ page.evaluate_in_frame(0, "window.__heard").unwrap(),+ serde_json::json!("TO-CHILD:true"),+ "the parent's message never reached the child"+ );+}++/// `window.postMessage(x, '*')` targets the same window, and its listener has+/// to hear it. This was a no-op stub, so a page posting to itself waited+/// forever.+#[tokio::test]+async fn window_post_message_delivers_to_the_same_window() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(+ r#"<!doctype html><html><body><script>+ window.__got = [];+ window.addEventListener('message', (e) => window.__got.push([String(e.data), e.isTrusted === true]));+ window.postMessage('SELF', '*');+ window.__syncGot = window.__got.length;+</script></body></html>"#,+ );++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(1000).await;++ assert_eq!(+ page.evaluate("window.__got"),+ serde_json::json!([["SELF", true]]),+ );+ // postMessage never delivers synchronously.+ assert_eq!(page.evaluate("window.__syncGot").as_f64(), Some(0.0));+}+/// A parser-created `<iframe src>` never goes through the `src` setter, so/// nothing used to start its load at all.#[tokio::test]