Skip to content

Truly independent web browser

LibWeb: Run window postMessage algorithms in Rust

Shannon Boothfa700128aabf
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
index ac6039ab142..bb6f3c96705 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
@@ -73,12 +73,8 @@ unsafe extern "C" {
data: u64,
ports: *const *mut c_void,
count: usize,
- ) -> *mut c_void;
- fn web_bindings_create_message_event_with_origin(
- realm: *mut c_void,
- r#type: ak::Span<'_, u8>,
- data: u64,
origin: *const FfiOrigin,
+ source: *mut c_void,
) -> *mut c_void;
fn web_bindings_message_event_data(event: u64) -> u64;
fn web_bindings_set_event_owner(event: *mut c_void, interface_name: u16, owner: *mut c_void);
@@ -260,43 +256,35 @@ impl CppEvent {
})
}
- /// A MessageEvent in the realm, https://html.spec.whatwg.org/multipage/comms.html#messageevent, with its data
- /// attribute initialized to the data and its ports attribute initialized to the MessagePorts that the objects are.
- pub(crate) fn create_message_event(realm: Gc<Realm>, r#type: &str, data: Value, ports: &[Gc<Object>]) -> Self {
- let ports: Vec<*mut c_void> = ports.iter().map(|port| port.as_ptr().cast()).collect();
- // SAFETY: The realm, the data and the ports are live, the type and the ports are lent for the call, and LibWeb
- // returns a live event.
- Self(unsafe {
- CppCell::from_raw(web_bindings_create_message_event(
- realm.as_ptr().cast(),
- ak::Span::new(r#type.as_bytes()),
- data.to_raw(),
- ports.as_ptr(),
- ports.len(),
- ))
- })
- }
-
- /// A MessageEvent in the realm with its data attribute initialized to the data and its origin attribute initialized
- /// to the serialization of the origin.
- pub(crate) fn create_message_event_with_origin(
+ /// A MessageEvent in the realm, https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ pub(crate) fn create_message_event(
realm: Gc<Realm>,
r#type: &str,
data: Value,
- origin: &Origin,
+ ports: &[Gc<Object>],
+ origin: Option<&Origin>,
+ source: Option<&CppCell>,
) -> Self {
- FfiOrigin::with_origin(origin, |origin| {
- // SAFETY: The realm and the data are live, the type and the origin are lent for the call, and LibWeb returns a
- // live event.
+ let ports: Vec<*mut c_void> = ports.iter().map(|port| port.as_ptr().cast()).collect();
+ let create = |origin: *const FfiOrigin| {
+ // SAFETY: The realm, the data, the ports and the source are live, the type, the ports and the origin are
+ // lent for the call, and LibWeb returns a live event.
Self(unsafe {
- CppCell::from_raw(web_bindings_create_message_event_with_origin(
+ CppCell::from_raw(web_bindings_create_message_event(
realm.as_ptr().cast(),
ak::Span::new(r#type.as_bytes()),
data.to_raw(),
+ ports.as_ptr(),
+ ports.len(),
origin,
+ source.map_or(core::ptr::null_mut(), CppCell::as_ptr),
))
})
- })
+ };
+ match origin {
+ Some(origin) => FfiOrigin::with_origin(origin, |origin| create(origin)),
+ None => create(core::ptr::null()),
+ }
}
pub(crate) fn set_owner<T: Interface>(&self, owner: Ref<T>) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
index 1658f527ab1..a6c25eac53f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
@@ -331,11 +331,13 @@ impl BroadcastChannel {
let Ok(data) = data else {
// If this throws an exception, catch it, fire an event named messageerror at destination, using MessageEvent, with its
// origin initialized to sourceOrigin, and then abort these steps.
- let event = CppEvent::create_message_event_with_origin(
+ let event = CppEvent::create_message_event(
target_realm,
"messageerror",
Value::NULL,
- &message.source_origin,
+ &[],
+ Some(&message.source_origin),
+ None,
);
event.set_is_trusted(true);
destination.event_target.dispatch_event(&event);
@@ -344,7 +346,8 @@ impl BroadcastChannel {
// 4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and
// its origin initialized to sourceOrigin.
- let event = CppEvent::create_message_event_with_origin(target_realm, "message", data, &message.source_origin);
+ let event =
+ CppEvent::create_message_event(target_realm, "message", data, &[], Some(&message.source_origin), None);
event.set_is_trusted(true);
destination.event_target.dispatch_event(&event);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index b96ffebcc83..7347e850418 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -8,7 +8,7 @@
//! handles, which Libraries/LibWeb/HTML/ImageData.cpp, Libraries/LibWeb/HTML/ImageBitmap.cpp and
//! Libraries/LibWeb/HTML/MessagePort.cpp declare. A cell is the cell of an object of the interface that the name of
//! the function says. Libraries/LibWeb/HTML/BroadcastChannel.cpp hands the BroadcastChannel objects the messages that
-//! other processes post.
+//! other processes post, and Libraries/LibWeb/HTML/Window.cpp runs the window post message steps.
use core::ffi::{c_int, c_void};
use core::ptr::NonNull;
@@ -24,16 +24,20 @@ use super::image_data::ImageData;
use super::message_port::MessagePort;
use super::storage::{Storage, StorageType};
use super::storage_event::{StorageEvent, StorageEventInit};
+use super::window::{PostedMessage, queue_posted_message, window_post_message_steps};
use crate::bindings::CallContext;
use crate::bindings::conversions::UsvString;
+use crate::bindings::cpp_cell::CppCell;
use crate::bindings::environment_settings_object::relevant_settings_object;
use crate::bindings::event_target::CppEventTarget;
use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments, wrap};
use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};
use crate::dom::event::EventInit;
+use crate::html::structured_serialize::cpp::SerializedTransferRecord;
use crate::html::structured_serialize::cpp::TransferDataDecoder;
use crate::html::structured_serialize::message_record::MessageRecord;
use crate::html::structured_serialize::transfer_data_holder::TransferDataHolder;
+use crate::html::structured_serialize::transfer_record::TransferRecord;
use crate::storage_api::storage_area_mirror::StorageEndpointType;
use crate::storage_api::storage_bottle::{obtain_a_local_storage_bottle_map, obtain_a_session_storage_bottle_map};
use crate::storage_api::storage_key::StorageKey;
@@ -50,6 +54,18 @@ unsafe fn object_from_abi<'a, T: Interface>(cell: *mut c_void) -> &'a T {
unsafe { &*object.as_ptr() }
}
+/// # Safety
+///
+/// `objects` must point to `count` live objects.
+unsafe fn objects_from_abi(vm: &Vm, objects: *const *mut c_void, count: usize) -> MarkedVec<'_, Gc<Object>> {
+ let list = MarkedVec::with_capacity(vm, count);
+ // SAFETY: The caller passes `count` live objects.
+ for &object in unsafe { ak::slice_from_raw_parts(objects, count) } {
+ list.push(unsafe { Gc::from_non_null(NonNull::new(object.cast::<Object>()).expect("C++ passes objects")) });
+ }
+ list
+}
+
/// Creates an ImageData of the size, with transparent black pixels and the sRGB color space, in the realm, and stores
/// its cell, or throws what initializing an ImageData throws.
///
@@ -279,13 +295,8 @@ pub unsafe extern "C" fn web_rust_message_port_post_message(
let mut cx = CallContext::new(vm, realm);
// SAFETY: The caller passes a live cell of a MessagePort and a live value.
let (port, message) = unsafe { (cell_from_abi::<MessagePort>(port), Value::from_raw(message)) };
- let transfer_list = MarkedVec::with_capacity(vm, count);
- for index in 0..count {
- // SAFETY: The caller passes `count` live objects.
- transfer_list.push(unsafe {
- Gc::from_non_null(NonNull::new((*transfer.add(index)).cast::<Object>()).expect("C++ passes objects"))
- });
- }
+ // SAFETY: The caller passes `count` live objects.
+ let transfer_list = unsafe { objects_from_abi(vm, transfer, count) };
let result = MessagePort::post_message(&port, &mut cx, message, transfer_list);
RawNativeFunctionResult::from_completion(
result
@@ -541,3 +552,60 @@ pub unsafe extern "C" fn web_rust_html_create_storage_event(vm: *mut c_void, rea
.event()
.as_ptr()
}
+
+/// # Safety
+///
+/// The VM, the realm, the target and the transferred objects must be live, and the target must be a Window if remote
+/// is false and a RemoteNavigable otherwise. The target origin string is handed over, and the transfer list is lent.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_window_post_message(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ target: *mut c_void,
+ remote: bool,
+ message: u64,
+ target_origin: usize,
+ transfer: *const *mut c_void,
+ count: usize,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let cx = CallContext::new(vm, realm);
+ // SAFETY: The caller lends the live target, message and transferred objects, and hands over the string.
+ let (target, message, target_origin, transfer) = unsafe {
+ (
+ CppCell::from_raw(target),
+ Value::from_raw(message),
+ Utf16String::from_raw_owned(target_origin),
+ objects_from_abi(vm, transfer, count),
+ )
+ };
+ let result = window_post_message_steps(&cx, target, remote, message, &target_origin, &transfer.values());
+ RawNativeFunctionResult::from_completion(result.map(|()| Value::UNDEFINED).map_err(|error| error.throw(&cx)))
+}
+
+/// # Safety
+///
+/// The VM, the Window and the source, if any, must be live, and the record and the origins are lent for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_window_queue_posted_message(
+ vm: *mut c_void,
+ target_window: *mut c_void,
+ record: *mut c_void,
+ target_origin: *const FfiOrigin,
+ origin: *const FfiOrigin,
+ source: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, and lends the Window, the source, the record and the origins.
+ unsafe {
+ let vm = &*vm.cast::<Vm>();
+ let posted_message = PostedMessage {
+ target_window: CppCell::from_raw(target_window),
+ serialize_with_transfer_result: TransferRecord::from_cpp(vm, SerializedTransferRecord::from_raw(record)),
+ target_origin: target_origin.as_ref().map(|origin| origin.to_origin()),
+ origin: (*origin).to_origin(),
+ source: NonNull::new(source).map(|source| CppCell::from_raw(source.as_ptr())),
+ };
+ queue_posted_message(vm, posted_message);
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
index 306b12cb625..292d2dc3b7c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
@@ -474,7 +474,7 @@ impl MessagePort {
TransferRecord::discard(serialize_with_transfer_result);
let Ok(deserialize_record) = deserialize_record else {
// If this throws an exception, catch it, fire an event named messageerror at messageEventTarget, using MessageEvent, and then return.
- let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[]);
+ let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], None, None);
event.set_is_trusted(true);
message_event_target.dispatch_event(&event);
return;
@@ -493,7 +493,8 @@ impl MessagePort {
}
// 7. Fire an event named message at messageEventTarget, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.
- let event = CppEvent::create_message_event(target_realm, "message", message_clone, &new_ports.values());
+ let event =
+ CppEvent::create_message_event(target_realm, "message", message_clone, &new_ports.values(), None, None);
event.set_is_trusted(true);
message_event_target.dispatch_event(&event);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 781998b4a78..d4bd261dadd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -80,3 +80,5 @@ pub(crate) mod storage_event;
pub(crate) mod structured_serialize;
#[cfg(not(test))]
pub(crate) mod text_metrics;
+#[cfg(not(test))]
+pub(crate) mod window;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/window.rs b/Libraries/LibWeb/Bindings/Rust/src/html/window.rs
new file mode 100644
index 00000000000..11bccf0a22b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/window.rs
@@ -0,0 +1,275 @@
+/*
+ * Copyright (c) 2020-2023, Andreas Kling <[email protected]>
+ * Copyright (c) 2021-2022, Sam Atkins <[email protected]>
+ * Copyright (c) 2021-2023, Linus Groh <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The window post message steps of Window,
+//! https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, MarkedVec, Object, Realm, Trace, Value, Vm, is_host_instance_of,
+};
+use liburl_rust::FfiOrigin;
+use liburl_rust::origin::Origin;
+
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEvent, CppEventTarget};
+use crate::bindings::interface::{Interface, with_temporary_execution_context_and_callbacks};
+use crate::bindings::promise::{TaskSource, queue_a_global_task};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::message_port::MessagePort;
+use crate::html::structured_serialize::transfer_record::{TransferRecord, TransferRecordRef};
+use crate::html::structured_serialize::{structured_deserialize_with_transfer, structured_serialize_with_transfer};
+
+type ReceiveOrigin = unsafe extern "C" fn(*mut c_void, *const FfiOrigin);
+
+unsafe extern "C" {
+ fn web_window_post_message_incumbent_settings() -> *mut c_void;
+ fn web_window_post_message_settings_origin(settings: *mut c_void, context: *mut c_void, receive: ReceiveOrigin);
+ fn web_window_post_message_source(settings: *mut c_void) -> *mut c_void;
+ fn web_window_post_message_parse_target_origin(target: usize, context: *mut c_void, receive: ReceiveOrigin);
+ fn web_window_post_message_realm(window: *mut c_void) -> *mut c_void;
+ fn web_window_post_message_document_origin(window: *mut c_void, context: *mut c_void, receive: ReceiveOrigin);
+ fn web_window_post_message_send_remote(
+ target: *mut c_void,
+ settings: *mut c_void,
+ record: *mut c_void,
+ target_origin: *const FfiOrigin,
+ source_origin: *const FfiOrigin,
+ source: *mut c_void,
+ );
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PostedMessage {
+ pub(crate) target_window: CppCell,
+ pub(crate) serialize_with_transfer_result: TransferRecordRef,
+ #[gc(untraced)]
+ pub(crate) target_origin: Option<Origin>,
+ #[gc(untraced)]
+ pub(crate) origin: Origin,
+ pub(crate) source: Option<CppCell>,
+}
+
+static POSTED_MESSAGE_CLASS: EmbedderClass<PostedMessage> = EmbedderClass::new("WindowPostedMessage");
+
+impl EmbedderValue for PostedMessage {
+ const CLASS: &'static EmbedderClass<Self> = &POSTED_MESSAGE_CLASS;
+}
+
+unsafe extern "C" fn receive_origin(context: *mut c_void, origin: *const FfiOrigin) {
+ // SAFETY: Each caller lends its result slot, and C++ lends a valid origin for the call.
+ unsafe { *context.cast::<Option<Origin>>() = Some((*origin).to_origin()) };
+}
+
+fn origin_of(cell: &CppCell, query: unsafe extern "C" fn(*mut c_void, *mut c_void, ReceiveOrigin)) -> Origin {
+ let mut origin = None;
+ // SAFETY: The cell is live, and the callback writes to the result slot while it is lent.
+ unsafe { query(cell.as_ptr(), (&raw mut origin).cast(), receive_origin) };
+ origin.expect("C++ lends the origin")
+}
+
+fn realm_of(window: &CppCell) -> Gc<Realm> {
+ // SAFETY: The window is live, and C++ returns its live principal realm.
+ unsafe {
+ Gc::from_non_null(
+ NonNull::new(web_window_post_message_realm(window.as_ptr()).cast()).expect("a Window has a realm"),
+ )
+ }
+}
+
+// https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
+pub(crate) fn window_post_message_steps(
+ cx: &CallContext,
+ target_window: CppCell,
+ remote: bool,
+ message: Value,
+ target_origin: &Utf16String,
+ transfer: &[Gc<Object>],
+) -> WebIdlResult<()> {
+ // 1. Let targetRealm be targetWindow's realm.
+ // NB: Taken from targetWindow when the queued task delivers the message.
+
+ // 2. Let incumbentSettings be the incumbent settings object.
+ // SAFETY: C++ returns the live incumbent settings object.
+ let incumbent_settings = unsafe { CppCell::from_raw(web_window_post_message_incumbent_settings()) };
+
+ // 3. Let targetOrigin be options["targetOrigin"].
+ let target_origin_units = target_origin.to_utf16();
+ let target_origin = if target_origin_units.as_ref() == [u16::from(b'/')] {
+ // 4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.
+ Some(origin_of(&incumbent_settings, web_window_post_message_settings_origin))
+ }
+ // 5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*):
+ else if target_origin_units.as_ref() != [u16::from(b'*')] {
+ // 1. Let parsedURL be the result of running the URL parser on targetOrigin.
+ let mut parsed_url_origin = None;
+ // SAFETY: The string and the result slot are lent for the call.
+ unsafe {
+ web_window_post_message_parse_target_origin(
+ target_origin.raw_identity(),
+ (&raw mut parsed_url_origin).cast(),
+ receive_origin,
+ );
+ }
+
+ // 2. If parsedURL is failure, then throw a "SyntaxError" DOMException.
+ let Some(parsed_url_origin) = parsed_url_origin else {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ Utf16String::from_utf8(&format!(
+ "Invalid URL for targetOrigin: '{}'",
+ String::from_utf16_lossy(&target_origin_units)
+ )),
+ ));
+ };
+
+ // 3. Set targetOrigin to parsedURL's origin.
+ Some(parsed_url_origin)
+ } else {
+ None
+ };
+
+ // 6. Let transfer be options["transfer"].
+ // 7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
+ let serialize_with_transfer_result = structured_serialize_with_transfer(cx, message, transfer)?;
+
+ // NB: The task queued by step 8 reads incumbentSettings in its steps 2 and 3. Snapshot those values here.
+ // 8.2. Let origin be incumbentSettings's origin.
+ let origin = origin_of(&incumbent_settings, web_window_post_message_settings_origin);
+
+ // 8.3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
+ // SAFETY: The settings object is live, and C++ returns its live WindowProxy.
+ let source = unsafe { CppCell::from_raw(web_window_post_message_source(incumbent_settings.as_ptr())) };
+
+ // 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
+ if remote {
+ // NB: targetWindow lives in the process hosting this navigable's document, so the task is a request to the UI
+ // process, which forwards it there. That process represents the source's navigable, which names the source.
+ // A source whose [[Window]] has no navigable is null there.
+ let serialize_with_transfer_result = TransferRecord::into_cpp(serialize_with_transfer_result, cx.vm());
+ FfiOrigin::with_origin(&origin, |origin| {
+ let send = |target_origin| {
+ // SAFETY: Every cell and origin is live, and the call takes over the record's contents.
+ unsafe {
+ web_window_post_message_send_remote(
+ target_window.as_ptr(),
+ incumbent_settings.as_ptr(),
+ serialize_with_transfer_result.record().as_raw(),
+ target_origin,
+ origin,
+ source.as_ptr(),
+ );
+ }
+ };
+ match &target_origin {
+ Some(target_origin) => FfiOrigin::with_origin(target_origin, |target_origin| send(target_origin)),
+ None => send(core::ptr::null()),
+ }
+ });
+ return Ok(());
+ }
+ queue_posted_message(
+ cx.vm(),
+ PostedMessage {
+ target_window,
+ serialize_with_transfer_result,
+ target_origin,
+ origin,
+ source: Some(source),
+ },
+ );
+ Ok(())
+}
+
+pub(crate) fn queue_posted_message(vm: &Vm, posted_message: PostedMessage) {
+ let posted_message = POSTED_MESSAGE_CLASS.allocate(vm, |_| posted_message);
+ queue_a_global_task(
+ vm,
+ realm_of(&posted_message.target_window).global_object(),
+ TaskSource::PostedMessage,
+ posted_message,
+ posted_message_task_steps,
+ );
+}
+
+fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMessage>>) {
+ let serialize_with_transfer_result = posted_message.serialize_with_transfer_result;
+
+ // 1. Let targetRealm be targetWindow's realm.
+ let target_realm = realm_of(&posted_message.target_window);
+
+ // 1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's
+ // associated Document's origin is not same origin with targetOrigin, then return.
+ // NB: Due to step 4 and 5 above, the only time it's not '*' is if target_origin contains an Origin.
+ if let Some(target_origin) = &posted_message.target_origin
+ && !origin_of(&posted_message.target_window, web_window_post_message_document_origin)
+ .is_same_origin(target_origin)
+ {
+ TransferRecord::discard(serialize_with_transfer_result);
+ return;
+ }
+
+ // 2. Let origin be incumbentSettings's origin.
+ // 3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
+ // NB: Both were snapshotted before the task was queued.
+ let origin = &posted_message.origin;
+ let source = posted_message.source.as_ref();
+
+ // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
+ // NB: The execution context must not stay on the stack while the event is dispatched, so that a microtask
+ // checkpoint can be performed after each listener.
+ let cx = CallContext::new(vm, target_realm);
+ let deserialize_record = with_temporary_execution_context_and_callbacks(target_realm, || {
+ structured_deserialize_with_transfer(&cx, serialize_with_transfer_result)
+ });
+ TransferRecord::discard(serialize_with_transfer_result);
+
+ // SAFETY: The target is a live Window, which is an EventTarget.
+ let target_window = unsafe { CppEventTarget::from_raw(posted_message.target_window.as_ptr()) };
+
+ // If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent,
+ // with its origin initialized to origin and the source attribute initialized to source, and then return.
+ let Ok(deserialize_record) = deserialize_record else {
+ let event =
+ CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], Some(origin), source);
+ target_window.dispatch_event(&event);
+ return;
+ };
+
+ // 5. Let messageClone be deserializeRecord.[[Deserialized]].
+ let message_clone = deserialize_record.deserialized;
+
+ // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]],
+ // if any, maintaining their relative order.
+ // FIXME: Use a FrozenArray
+ let new_ports = MarkedVec::new(vm);
+ for &value in deserialize_record.transferred_values.values().iter() {
+ if is_host_instance_of(&value, MessagePort::wrapper_class()) {
+ new_ports.push(value);
+ }
+ }
+
+ // 7. Fire an event named message at targetWindow, using MessageEvent, with its origin initialized to origin,
+ // the source attribute initialized to source, the data attribute initialized to messageClone, and the ports
+ // attribute initialized to newPorts.
+ let event = CppEvent::create_message_event(
+ target_realm,
+ "message",
+ message_clone,
+ &new_ports.values(),
+ Some(origin),
+ source,
+ );
+ event.set_is_trusted(true);
+ target_window.dispatch_event(&event);
+}
diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
index 3c6d7fc68f4..dcad910183b 100644
--- a/Libraries/LibWeb/Bindings/RustEventTarget.cpp
+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
@@ -15,6 +15,7 @@
#include <LibWeb/HTML/MessageEvent.h>
#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/WebIDL/CallbackType.h>
@@ -117,8 +118,7 @@ void web_bindings_add_event_listener_without_options(DOM::EventTarget*, Readonly
void web_bindings_remove_event_listener_without_options(DOM::EventTarget*, ReadonlyBytes type, WebIDL::CallbackType*);
DOM::Event* web_bindings_create_event(void* realm, ReadonlyBytes type, bool bubbles, bool cancelable, bool composed);
RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubbles, bool cancelable, bool composed);
-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count);
-DOM::Event* web_bindings_create_message_event_with_origin(void* realm, ReadonlyBytes type, JSValue data, URL::FFI::FfiOrigin const* origin);
+DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, HTML::WindowProxy* source);
JSValue web_bindings_message_event_data(JSValue event);
void web_bindings_set_event_owner(RustEvent*, u16 interface_name, RustInterfaceCell* owner);
void web_bindings_event_set_is_trusted(DOM::Event*, bool is_trusted);
@@ -202,25 +202,22 @@ RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubble
return RustEvent::create(Utf16FlyString::from_utf16(type_string.utf16_view()), event_init, HighResolutionTime::current_high_resolution_time(js_realm.global_object())).ptr();
}
-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count)
+DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, HTML::WindowProxy* source)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
HTML::MessageEventInit event_init;
event_init.data = JS::HostABI::value_from_abi(data);
+ if (source)
+ event_init.source = GC::Ref { *source };
for (size_t i = 0; i < count; ++i) {
auto* port = impl_from<HTML::MessagePort>(JS::HostABI::object_from_abi(ports[i]));
VERIFY(port);
event_init.ports.append(*port);
}
- return HTML::MessageEvent::create(js_realm.global_object(), Utf16FlyString::from_utf8_without_validation(type), event_init).ptr();
-}
-
-DOM::Event* web_bindings_create_message_event_with_origin(void* realm, ReadonlyBytes type, JSValue data, URL::FFI::FfiOrigin const* origin)
-{
- auto& js_realm = *static_cast<JS::Realm*>(realm);
- HTML::MessageEventInit event_init;
- event_init.data = JS::HostABI::value_from_abi(data);
- return HTML::MessageEvent::create(js_realm.global_object(), Utf16FlyString::from_utf8_without_validation(type), event_init, URL::RustIntegration::origin_from_ffi(*origin)).ptr();
+ auto event_type = Utf16FlyString::from_utf8_without_validation(type);
+ if (!origin)
+ return HTML::MessageEvent::create(js_realm.global_object(), event_type, event_init).ptr();
+ return HTML::MessageEvent::create(js_realm.global_object(), event_type, event_init, URL::RustIntegration::origin_from_ffi(*origin)).ptr();
}
JSValue web_bindings_message_event_data(JSValue event)
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 2d9afb1038f..c86ccc625d2 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -3569,10 +3569,7 @@ void LocalNavigable::deliver_posted_message_from_another_process(MessageDescript
}
// 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
- queue_global_task(Task::Source::PostedMessage, relevant_global_object(*window), GC::create_function(heap(), [window, source, message = move(message)]() mutable {
- // NB: deliver_posted_message() runs these steps.
- window->deliver_posted_message(move(message.serialize_with_transfer_result), message.target_origin, message.source_origin, source);
- }));
+ window->queue_posted_message(move(message.serialize_with_transfer_result), message.target_origin, message.source_origin, source);
}
// Continue the navigate algorithm at step 9 with the values prepared by steps 1-7 in navigate().
diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cpp
index 0dae7b265b3..ba20313455e 100644
--- a/Libraries/LibWeb/HTML/MessagePort.cpp
+++ b/Libraries/LibWeb/HTML/MessagePort.cpp
@@ -114,17 +114,3 @@ void MessagePort::fail_next_transfer_for_testing()
}
}
-
-namespace Web::Bindings {
-
-GC::RootVector<GC::Ref<HTML::MessagePort>> message_ports_from_transferred_values(Vector<GC::Root<JS::Object>> const& transferred_values)
-{
- GC::RootVector<GC::Ref<HTML::MessagePort>> ports;
- for (auto const& object : transferred_values) {
- if (auto* message_port = impl_from<HTML::MessagePort>(object.ptr()))
- ports.append(*message_port);
- }
- return ports;
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/MessagePort.h b/Libraries/LibWeb/HTML/MessagePort.h
index 9b5e18df219..4a016770ef5 100644
--- a/Libraries/LibWeb/HTML/MessagePort.h
+++ b/Libraries/LibWeb/HTML/MessagePort.h
@@ -56,9 +56,3 @@ public:
};
}
-
-namespace Web::Bindings {
-
-WEB_API GC::RootVector<GC::Ref<HTML::MessagePort>> message_ports_from_transferred_values(Vector<GC::Root<JS::Object>> const&);
-
-}
diff --git a/Libraries/LibWeb/HTML/RemoteWindow.cpp b/Libraries/LibWeb/HTML/RemoteWindow.cpp
index 6b3f5b65787..f692090ab77 100644
--- a/Libraries/LibWeb/HTML/RemoteWindow.cpp
+++ b/Libraries/LibWeb/HTML/RemoteWindow.cpp
@@ -5,6 +5,7 @@
*/
#include <LibGC/Heap.h>
+#include <LibURL/RustIntegration.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/Location.h>
#include <LibWeb/HTML/NavigationSourceSnapshot.h>
@@ -234,35 +235,32 @@ WebIDL::ExceptionOr<void> RemoteWindow::post_message(JS::Realm& realm, JS::Value
{
// The Window interface's postMessage(message, options) method steps are to run the window post message steps given
// this, message, and options.
+ return Window::window_post_message_steps(realm, m_navigable, message, options);
+}
- // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
- // 1. Let targetRealm be targetWindow's realm.
- // NB: Taken from targetWindow when the task delivers the message in its process.
-
- // 2-7.
- auto prepared = TRY(Window::prepare_post_message(realm, message, options));
+extern "C" void web_window_post_message_send_remote(RemoteNavigable* target, EnvironmentSettingsObject* settings, SerializedTransferRecord* record, URL::FFI::FfiOrigin const* target_origin, URL::FFI::FfiOrigin const* source_origin, WindowProxy* source);
- // 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
- // NB: targetWindow lives in the process hosting this navigable's document, so the task is a request to the UI
- // process, which forwards it there. That process represents the source's navigable, which names the source.
- // A source whose [[Window]] has no navigable is null there.
+void web_window_post_message_send_remote(RemoteNavigable* target, EnvironmentSettingsObject* settings, SerializedTransferRecord* record, URL::FFI::FfiOrigin const* target_origin, URL::FFI::FfiOrigin const* source_origin, WindowProxy* source)
+{
Optional<CrossProcessId> source_navigable_id;
// AD-HOC: The UI process takes the source only from a navigable this process hosts, so a source whose [[Window]] is
// in another process is null.
// NB: A navigable in a destroyed subtree is discarded, like it is for the source's window.parent.
- if (auto window = prepared.source->window()) {
+ if (auto window = source->window()) {
if (auto source_navigable = window->navigable(); source_navigable && !source_navigable->is_in_a_destroyed_subtree())
source_navigable_id = source_navigable->id();
}
+ Variant<Utf16String, URL::Origin> target_origin_value = u"*"_utf16;
+ if (target_origin)
+ target_origin_value = URL::RustIntegration::origin_from_ffi(*target_origin);
PostedMessageDescriptor posted_message {
- .serialize_with_transfer_result = move(prepared.serialize_with_transfer_result),
- .target_origin = move(prepared.target_origin),
- .incumbent_settings_id = move(prepared.incumbent_settings_id),
- .source_origin = move(prepared.source_origin),
+ .serialize_with_transfer_result = move(*record),
+ .target_origin = move(target_origin_value),
+ .incumbent_settings_id = settings->id,
+ .source_origin = URL::RustIntegration::origin_from_ffi(*source_origin),
.source_navigable_id = source_navigable_id,
};
- m_navigable->page().client().request_post_message_to_remote_navigable(*m_navigable, move(posted_message));
- return {};
+ target->page().client().request_post_message_to_remote_navigable(*target, move(posted_message));
}
// https://html.spec.whatwg.org/multipage/document-sequences.html#document-tree-child-navigables
diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cpp
index dd9b1057c6e..be742ee1546 100644
--- a/Libraries/LibWeb/HTML/Window.cpp
+++ b/Libraries/LibWeb/HTML/Window.cpp
@@ -11,6 +11,7 @@
#include <LibGC/Heap.h>
#include <LibGC/WeakHashSet.h>
#include <LibIPC/File.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/Error.h>
@@ -19,6 +20,7 @@
#include <LibJS/Runtime/NativeFunction.h>
#include <LibTextCodec/Decoder.h>
#include <LibURL/Origin.h>
+#include <LibURL/RustIntegration.h>
#include <LibWeb/Bindings/IdleRequest.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
@@ -62,7 +64,6 @@
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/LocalTraversableNavigable.h>
#include <LibWeb/HTML/Location.h>
-#include <LibWeb/HTML/MessageEvent.h>
#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Navigation.h>
#include <LibWeb/HTML/Navigator.h>
@@ -1623,128 +1624,72 @@ Optional<Utf16String> Window::prompt(Optional<Utf16String> const& message, Optio
return result;
}
-WebIDL::ExceptionOr<Window::PreparedPostMessage> Window::prepare_post_message(JS::Realm& realm, JS::Value message, PostMessageOptions const& options)
-{
- // 2. Let incumbentSettings be the incumbent settings object.
- auto& incumbent_settings = incumbent_settings_object();
-
- // 3. Let targetOrigin be options["targetOrigin"].
- Variant<Utf16String, URL::Origin> target_origin = options.target_origin;
+extern "C" {
+JSCompletion web_window_post_message(JSVM*, void* realm, void* target, bool remote, JSValue, FlatPtr target_origin, JSObject* const* transfer, size_t count);
+void web_window_queue_posted_message(JSVM*, Window*, SerializedTransferRecord*, URL::FFI::FfiOrigin const* target_origin, URL::FFI::FfiOrigin const* source_origin, WindowProxy* source);
+EnvironmentSettingsObject* web_window_post_message_incumbent_settings();
+void web_window_post_message_settings_origin(EnvironmentSettingsObject*, void*, void (*)(void*, URL::FFI::FfiOrigin const*));
+WindowProxy* web_window_post_message_source(EnvironmentSettingsObject*);
+void web_window_post_message_parse_target_origin(FlatPtr, void*, void (*)(void*, URL::FFI::FfiOrigin const*));
+void* web_window_post_message_realm(Window*);
+void web_window_post_message_document_origin(Window*, void*, void (*)(void*, URL::FFI::FfiOrigin const*));
+}
- // 4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.
- if (options.target_origin == u"/"sv) {
- target_origin = incumbent_settings.origin();
- }
- // 5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*), then:
- else if (options.target_origin != u"*"sv) {
- // 1. Let parsedURL be the result of running the URL parser on targetOrigin.
- auto parsed_url = DOMURL::parse(options.target_origin.utf16_view());
-
- // 2. If parsedURL is failure, then throw a "SyntaxError" DOMException.
- if (!parsed_url.has_value())
- return Web::throw_completion(
- realm,
- WebIDL::SyntaxError::create(Utf16String::formatted("Invalid URL for targetOrigin: '{}'", options.target_origin)));
-
- // 3. Set targetOrigin to parsedURL's origin.
- target_origin = parsed_url->origin();
- }
+EnvironmentSettingsObject* web_window_post_message_incumbent_settings()
+{
+ return &incumbent_settings_object();
+}
- // 6. Let transfer be options["transfer"].
- auto& transfer = options.structured_serialize_options.transfer;
+void web_window_post_message_settings_origin(EnvironmentSettingsObject* settings, void* context, void (*receive)(void*, URL::FFI::FfiOrigin const*))
+{
+ URL::RustIntegration::lend_origin_to_ffi(settings->origin(), [&](auto const& origin) { receive(context, &origin); });
+}
- // 7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
- auto serialize_with_transfer_result = TRY(structured_serialize_with_transfer(realm, message, transfer));
+WindowProxy* web_window_post_message_source(EnvironmentSettingsObject* settings)
+{
+ return window_proxy_from_global_this_value(settings->realm().global_environment().global_this_value()).ptr();
+}
- // NB: The task queued by step 8 reads incumbentSettings in its steps 2 and 3. Snapshot those values here.
- // 8.2. Let origin be the incumbentSettings's origin.
- auto source_origin = incumbent_settings.origin();
+void web_window_post_message_parse_target_origin(FlatPtr raw_target_origin, void* context, void (*receive)(void*, URL::FFI::FfiOrigin const*))
+{
+ // DOMURL parsing also resolves blob URL entries, whose stored origin takes precedence over parsing their path.
+ auto target_origin = Utf16String::from_raw(raw_target_origin);
+ if (auto url = DOMURL::parse(target_origin.utf16_view()); url.has_value())
+ URL::RustIntegration::lend_origin_to_ffi(url->origin(), [&](auto const& origin) { receive(context, &origin); });
+}
- // 8.3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
- auto source = window_proxy_from_global_this_value(incumbent_settings.realm().global_environment().global_this_value());
+void* web_window_post_message_realm(Window* window)
+{
+ return &window->principal_realm();
+}
- return PreparedPostMessage {
- .serialize_with_transfer_result = move(serialize_with_transfer_result),
- .target_origin = move(target_origin),
- .incumbent_settings_id = incumbent_settings.id,
- .source_origin = move(source_origin),
- .source = source,
- };
+void web_window_post_message_document_origin(Window* window, void* context, void (*receive)(void*, URL::FFI::FfiOrigin const*))
+{
+ URL::RustIntegration::lend_origin_to_ffi(window->document()->origin(), [&](auto const& origin) { receive(context, &origin); });
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
-WebIDL::ExceptionOr<void> Window::window_post_message_steps(JS::Realm& realm, JS::Value message, PostMessageOptions const& options)
+WebIDL::ExceptionOr<void> Window::window_post_message_steps(JS::Realm& realm, Variant<GC::Ref<Window>, GC::Ref<RemoteNavigable>> target_window, JS::Value message, PostMessageOptions const& options)
{
- // 1. Let targetRealm be targetWindow's realm.
- // NB: Taken from targetWindow when the queued task delivers the message.
-
- // 2-7.
- auto prepared = TRY(prepare_post_message(realm, message, options));
-
- // 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
- queue_global_task(Task::Source::PostedMessage, relevant_global_object(*this), GC::create_function(GC::Heap::the(), [this, prepared = move(prepared)]() mutable {
- deliver_posted_message(move(prepared.serialize_with_transfer_result), prepared.target_origin, prepared.source_origin, prepared.source);
- }));
-
+ auto* target = target_window.visit([](auto target) -> void* { return target.ptr(); });
+ Vector<JSObject*> transfer;
+ for (auto const& object : options.structured_serialize_options.transfer)
+ transfer.append(JS::HostABI::object_to_abi(object.ptr()));
+ TRY(JS::HostABI::completion_from_abi<void>(web_window_post_message(JS::HostABI::vm_to_abi(realm.vm()), &realm, target, target_window.has<GC::Ref<RemoteNavigable>>(), JS::HostABI::value_to_abi(message), options.target_origin.to_raw_leaked(), transfer.data(), transfer.size())));
return {};
}
-void Window::deliver_posted_message(SerializedTransferRecord serialize_with_transfer_result, Variant<Utf16String, URL::Origin> const& target_origin, URL::Origin const& origin, GC::Ptr<WindowProxy> source)
+void Window::queue_posted_message(SerializedTransferRecord record, Variant<Utf16String, URL::Origin> const& target_origin, URL::Origin const& source_origin, GC::Ptr<WindowProxy> source)
{
- // 1. Let targetRealm be targetWindow's realm.
- auto& target_realm = principal_realm();
-
- // 1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's
- // associated Document's origin is not same origin with targetOrigin, then return.
- // NOTE: Due to step 4 and 5 above, the only time it's not '*' is if target_origin contains an Origin.
- if (!target_origin.has<Utf16String>()) {
- auto const& actual_target_origin = target_origin.get<URL::Origin>();
- if (!document()->origin().is_same_origin(actual_target_origin))
- return;
- }
-
- // 2. Let origin be the incumbentSettings's origin.
- // 3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
- // NB: Both were snapshotted by prepare_post_message().
- NullableMessageEventSource source_for_event = Empty {};
- if (source)
- source_for_event = GC::Ref { *source };
-
- // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
- // NB: The execution context must not stay on the stack while the event is dispatched, so that a microtask
- // checkpoint can be performed after each listener.
- auto deserialize_record_or_error = [&] {
- TemporaryExecutionContext temporary_execution_context { target_realm, TemporaryExecutionContext::CallbacksEnabled::Yes };
- return structured_deserialize_with_transfer(serialize_with_transfer_result, target_realm);
- }();
-
- // If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent,
- // with its origin initialized to origin and the source attribute initialized to source, and then return.
- if (deserialize_record_or_error.is_exception()) {
- MessageEventInit message_event_init { {}, JS::js_null(), Utf16String {}, Utf16String {}, {}, source_for_event };
-
- auto message_error_event = MessageEvent::create(target_realm.global_object(), EventNames::messageerror, message_event_init, origin);
- dispatch_event(message_error_event);
- return;
- }
-
- // 5. Let messageClone be deserializeRecord.[[Deserialized]].
- auto deserialize_record = deserialize_record_or_error.release_value();
- auto message_clone = deserialize_record.deserialized;
-
- // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]],
- // if any, maintaining their relative order.
- // FIXME: Use a FrozenArray
- auto new_ports = Bindings::message_ports_from_transferred_values(deserialize_record.transferred_values);
-
- // 7. Fire an event named message at targetWindow, using MessageEvent, with its origin initialized to origin,
- // the source attribute initialized to source, the data attribute initialized to messageClone, and the ports
- // attribute initialized to newPorts.
- MessageEventInit message_event_init { {}, message_clone, Utf16String {}, Utf16String {}, move(new_ports), source_for_event };
-
- auto message_event = MessageEvent::create(target_realm.global_object(), EventNames::message, message_event_init, origin);
- message_event->set_is_trusted(true);
- dispatch_event(message_event);
+ URL::RustIntegration::lend_origin_to_ffi(source_origin, [&](auto const& source_origin) {
+ auto queue = [&](URL::FFI::FfiOrigin const* target) {
+ web_window_queue_posted_message(JS::HostABI::vm_to_abi(vm()), this, &record, target, &source_origin, source.ptr());
+ };
+ if (target_origin.has<URL::Origin>())
+ URL::RustIntegration::lend_origin_to_ffi(target_origin.get<URL::Origin>(), [&](auto const& target) { queue(&target); });
+ else
+ queue(nullptr);
+ });
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage-options
@@ -1752,7 +1697,7 @@ WebIDL::ExceptionOr<void> Window::post_message(JS::Realm& realm, JS::Value messa
{
// The Window interface's postMessage(message, options) method steps are to run the window post message steps given
// this, message, and options.
- return window_post_message_steps(realm, message, options);
+ return window_post_message_steps(realm, GC::Ref { *this }, message, options);
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
@@ -1760,7 +1705,7 @@ WebIDL::ExceptionOr<void> Window::post_message(JS::Realm& realm, JS::Value messa
{
// The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message
// steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».
- return window_post_message_steps(realm, message, PostMessageOptions { { .transfer = transfer }, target_origin });
+ return window_post_message_steps(realm, GC::Ref { *this }, message, PostMessageOptions { { .transfer = transfer }, target_origin });
}
// https://dom.spec.whatwg.org/#dom-window-event
diff --git a/Libraries/LibWeb/HTML/Window.h b/Libraries/LibWeb/HTML/Window.h
index 6ce69f476d3..8fb64425b5b 100644
--- a/Libraries/LibWeb/HTML/Window.h
+++ b/Libraries/LibWeb/HTML/Window.h
@@ -231,15 +231,8 @@ public:
Utf16String target_origin;
};
WebIDL::ExceptionOr<void> post_message(JS::Realm&, JS::Value message, PostMessageOptions const&);
- struct PreparedPostMessage {
- SerializedTransferRecord serialize_with_transfer_result;
- Variant<Utf16String, URL::Origin> target_origin;
- EnvironmentId incumbent_settings_id;
- URL::Origin source_origin;
- GC::Ref<WindowProxy> source;
- };
- static WebIDL::ExceptionOr<PreparedPostMessage> prepare_post_message(JS::Realm&, JS::Value message, PostMessageOptions const&);
- void deliver_posted_message(SerializedTransferRecord, Variant<Utf16String, URL::Origin> const& target_origin, URL::Origin const& source_origin, GC::Ptr<WindowProxy> source);
+ static WebIDL::ExceptionOr<void> window_post_message_steps(JS::Realm&, Variant<GC::Ref<Window>, GC::Ref<RemoteNavigable>> target_window, JS::Value, PostMessageOptions const&);
+ void queue_posted_message(SerializedTransferRecord, Variant<Utf16String, URL::Origin> const& target_origin, URL::Origin const& source_origin, GC::Ptr<WindowProxy> source);
Variant<GC::Ref<DOM::Event>, Empty> event() const;
@@ -349,8 +342,6 @@ private:
};
NamedObjects named_objects(Utf16View name);
- WebIDL::ExceptionOr<void> window_post_message_steps(JS::Realm&, JS::Value, PostMessageOptions const&);
-
// https://html.spec.whatwg.org/multipage/window-object.html#concept-document-window
GC::Ptr<DOM::Document> m_associated_document;
GC::Ptr<WindowEnvironmentSettingsObject> m_environment_settings_object;
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 171f991e398..fa89022ecbe 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -61,8 +61,8 @@ ALLOWED_REALM_MENTIONS = {
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
63,
- 171,
- "HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
+ 169,
+ "HTML algorithms still contain structured serialization, including canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; window postMessage glue supplies principal realms and routes remote messages; "
"the C++ glue of the Rust structured serialization creates platform objects and SharedArrayBuffers in a given realm; "
"the C++ glue of the Rust Storage and StorageEvent creates them in a given realm",
),