Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(history): isolate Navigation wrappers and share event dispatch

ldm0248fc5c0f5f5
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index 8c85f026a..79112d9d3 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -25,6 +25,16 @@ observed, but it does not replace the executable probe when one can be run. If
Chromium cannot be tested, document that limitation explicitly instead of
presenting an inferred expectation as verified behavior.
+The `history-worlds` group was calibrated on 2026-09-25 against macOS Google
+Chrome 154.0.8037.57 using a fresh headless profile. It uses a real CDP WebSocket
+and `Page.createIsolatedWorld` to cover the PR #818 regressions: entry wrapper
+identity and expando/method isolation, one `currententrychange` in each world,
+isolated `navigate` cancellation, and the realm of History `SecurityError`s.
+It also verifies that a later main-world mutation updates the isolated world's
+structured state and preserves its local state cache. Run it with
+`uv run moli-cdp-smoke --group history-worlds`, or add `--endpoint URL` to use an
+existing browser process.
+
The detailed `emulation-storage` locale/timezone matrix was calibrated on
2026-09-01 against Debian Chromium 145.0.7632.116. In addition to resolved
locale, timezone, local getters, and formatted strings, the executable probe
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py b/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py
new file mode 100644
index 000000000..bf4c70e16
--- /dev/null
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/history_worlds.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import asyncio
+from contextlib import suppress
+from typing import Any
+
+from ..assertions import SmokeError, assert_equal, record
+from ..raw_cdp import connect_raw_cdp
+
+
+async def run_history_worlds_group(
+ endpoint: str, fixture: str, results: list[dict[str, Any]]
+) -> None:
+ """Exercise PR #818's world boundaries through a real CDP connection."""
+ client = await connect_raw_cdp(endpoint)
+ browser_context: str | None = None
+ session: str | None = None
+
+ async def command(method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
+ message_id = await client.send(method, params, session_id=session)
+ response, _ = await client.recv_until_id(message_id, timeout=10)
+ if "error" in response:
+ raise SmokeError(f"{method}: {response['error']!r}")
+ return response["result"]
+
+ async def evaluate(source: str, context: int | None = None) -> Any:
+ params: dict[str, Any] = {"expression": source, "returnByValue": True}
+ if context is not None:
+ params["contextId"] = context
+ response = await command("Runtime.evaluate", params)
+ if "exceptionDetails" in response:
+ raise SmokeError(f"history world evaluation: {response['exceptionDetails']!r}")
+ return response["result"].get("value")
+
+ try:
+ browser_context = (await command("Target.createBrowserContext"))["browserContextId"]
+ target = (await command("Target.createTarget", {
+ "url": "about:blank", "browserContextId": browser_context,
+ }))["targetId"]
+ session = (await command("Target.attachToTarget", {
+ "targetId": target, "flatten": True,
+ }))["sessionId"]
+ await command("Runtime.enable")
+ await command("Page.enable")
+ navigate_id = await client.send("Page.navigate", {"url": f"{fixture}/plain"}, session_id=session)
+ navigation = None
+ loaded = False
+ async with asyncio.timeout(10):
+ while navigation is None or not loaded:
+ message = await client.recv()
+ if message.get("id") == navigate_id:
+ if "error" in message:
+ raise SmokeError(f"Page.navigate: {message['error']!r}")
+ navigation = message["result"]
+ if message.get("sessionId") == session and message.get("method") == "Page.loadEventFired":
+ loaded = True
+ if navigation.get("errorText"):
+ raise SmokeError(f"history world navigation: {navigation!r}")
+ frame = (await command("Page.getFrameTree"))["frameTree"]["frame"]["id"]
+ await evaluate("""
+ history.replaceState({value: 1}, '', '#one');
+ navigation.updateCurrentEntry({state: {value: 7}});
+ navigation.currentEntry.expando = 'page';
+ navigation.currentEntry.getState = () => 'page-override';
+ globalThis.pageChanges = 0;
+ navigation.addEventListener('currententrychange', () => pageChanges++);
+ """)
+ isolated = (await command("Page.createIsolatedWorld", {
+ "frameId": frame, "worldName": "history-native-regression",
+ }))["executionContextId"]
+ wrappers = await evaluate("""
+ [navigation.currentEntry instanceof NavigationHistoryEntry,
+ navigation.currentEntry.expando === undefined,
+ navigation.currentEntry.getState().value,
+ navigation.entries().includes(navigation.currentEntry),
+ Object.getPrototypeOf(history.state) === Object.prototype]
+ """, isolated)
+ assert_equal(wrappers, [True, True, 7, True, True], "Navigation entry world wrappers")
+
+ changes = await evaluate("""
+ globalThis.changes = 0;
+ const previous = navigation.currentEntry;
+ globalThis.changeViews = [];
+ navigation.addEventListener('currententrychange', function (event) {
+ changes++;
+ changeViews.push([this === navigation, event.target === navigation,
+ event instanceof NavigationCurrentEntryChangeEvent,
+ event.from instanceof NavigationHistoryEntry, event.from === previous]);
+ });
+ history.pushState({value: 2}, '', '#two');
+ [changes, changeViews]
+ """, isolated)
+ assert_equal(changes, [1, [[True] * 5]], "one currententrychange in isolated world")
+ assert_equal(await evaluate("pageChanges"), 1, "one currententrychange in page world")
+
+ cancellation = await evaluate("""
+ (() => {
+ const before = location.href;
+ const length = history.length;
+ let seen = 0;
+ navigation.addEventListener('navigate', function (event) {
+ seen++;
+ event.preventDefault();
+ }, {once: true});
+ history.pushState({}, '', '#must-not-commit');
+ return [seen, location.href === before, history.length === length];
+ })()
+ """, isolated)
+ assert_equal(cancellation, [1, True, True], "isolated navigate listener cancels commit")
+
+ errors = await evaluate("""
+ ['pushState', 'replaceState'].map(method => {
+ try { history[method]({}, '', 'https://other.invalid/'); }
+ catch (error) { return [error.name, error instanceof DOMException,
+ Object.getPrototypeOf(error) === DOMException.prototype]; }
+ return ['did not throw'];
+ })
+ """, isolated)
+ assert_equal(errors, [["SecurityError", True, True]] * 2, "History error realm")
+
+ await evaluate("history.pushState({value: 3, map: new Map([['x', 2n]])}, '', '#three')")
+ state = await evaluate("""
+ [history.state.value, history.state.map instanceof Map,
+ history.state.map.get('x') === 2n, history.state === history.state,
+ changes]
+ """, isolated)
+ assert_equal(state, [3, True, True, True, 2], "native History updates reach existing worlds")
+ record(results, "raw_cdp_history_world_boundaries", {
+ "wrappers": wrappers, "changes": changes, "cancellation": cancellation,
+ "errors": errors, "state": state,
+ })
+ finally:
+ session = None
+ if browser_context is not None:
+ with suppress(Exception):
+ await command("Target.disposeBrowserContext", {"browserContextId": browser_context})
+ await client.websocket.close()
diff --git a/moli-cdp-smoke/moli_cdp_smoke/runner.py b/moli-cdp-smoke/moli_cdp_smoke/runner.py
index 3fb4b364d..6ac55c0ee 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/runner.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/runner.py
@@ -36,6 +36,7 @@ from .groups.document_content import run_document_content_group
from .groups.emulation_storage import run_emulation_storage_group
from .groups.error_document import run_error_document_group
from .groups.fetch_runtime_teardown import run_fetch_runtime_teardown_group
+from .groups.history_worlds import run_history_worlds_group
from .groups.inspector_routing import run_inspector_routing_group
from .groups.iframe_input import run_iframe_input_group
from .groups.layout_screenshot import run_layout_screenshot_group
@@ -200,6 +201,12 @@ RAW_GROUPS: tuple[SmokeGroup, ...] = (
"raw",
run_raw_protocol_group,
),
+ SmokeGroup(
+ "history-worlds",
+ "Native history with isolated-world entries, Navigation listeners, cancellation, and errors.",
+ "raw",
+ run_history_worlds_group,
+ ),
)
PAGE_GROUPS: tuple[SmokeGroup, ...] = (
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 54ab3be4b..980e071dd 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -55,6 +55,7 @@ mod navigation_cancellation;
mod navigation_cross_document;
mod navigation_entry;
mod navigation_entry_state;
+mod navigation_event_worlds;
mod navigation_events;
mod navigation_handler_callbacks;
mod navigation_history_pruning;
@@ -67,6 +68,7 @@ mod navigation_result;
mod navigation_seed;
mod navigation_serialize;
mod navigation_surface;
+mod navigation_transition_worlds;
mod navigation_traversal;
mod navigation_traversal_coordinator;
mod navigation_traversal_execution;
@@ -74,6 +76,7 @@ mod navigation_traversal_plan;
mod navigation_window;
mod navigator_runtime;
mod session_history;
+mod shared_event_targets;
#[cfg(test)]
pub(crate) use navigator_runtime::{
materialized_navigator_subobject_keys, navigator_storage_wrapper_diagnostics,
diff --git a/moli-renderer-v8/src/context_bootstrap/event_legacy.rs b/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
index 66052503b..d2a4cb564 100644
--- a/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
+++ b/moli-renderer-v8/src/context_bootstrap/event_legacy.rs
@@ -295,7 +295,7 @@ pub(super) fn event_init_event_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- let event = args.this();
+ let event = super::events::event_backing(scope, args.this());
if event_is_dispatching(scope, event) {
return;
}
diff --git a/moli-renderer-v8/src/context_bootstrap/events.rs b/moli-renderer-v8/src/context_bootstrap/events.rs
index f146429af..a3814a4b9 100644
--- a/moli-renderer-v8/src/context_bootstrap/events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events.rs
@@ -228,6 +228,7 @@ pub(crate) use base::{
event_internal_bool_flag, event_is_dispatching, initialize_event_object, mark_event_trusted,
set_event_composed_path, set_event_internal_flag, set_event_trusted,
};
+pub(in crate::context_bootstrap) use base::{bind_event_backing, event_backing, event_trusted};
fn event_subclass_kind<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
@@ -347,10 +348,12 @@ pub(super) use methods::{
event_stop_immediate_propagation_callback, event_stop_propagation_callback,
event_time_stamp_getter_function, set_event_default_prevented,
};
-pub(in crate::context_bootstrap) use subclasses::run_navigate_event_precommit_handlers;
pub(super) use subclasses::{
build_event_subclass_template, pointer_event_get_predicted_events_callback,
};
+pub(in crate::context_bootstrap) use subclasses::{
+ navigation_precommit_controller_for_event, run_navigate_event_precommit_handlers,
+};
pub(in crate::context_bootstrap) fn finalize_pointer_event_realm_bindings<'s>(
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/events/base.rs b/moli-renderer-v8/src/context_bootstrap/events/base.rs
index dc90dc0f8..fc9b3ab18 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/base.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/base.rs
@@ -15,6 +15,88 @@ const EVENT_INITIALIZED_SLOT: &str = "__moliEventInitialized";
const EVENT_TRUSTED_PRIVATE_SLOT: &str = "__moliEventTrusted";
const EVENT_TIMESTAMP_PRIVATE_SLOT: &str = "__moliEventTimeStamp";
const EVENT_IS_TRUSTED_GETTER_FUNCTION_SLOT: &str = "__moliEventIsTrustedGetterFunction";
+const EVENT_BACKING_SLOT: &str = "__moliEventBacking";
+
+pub(in crate::context_bootstrap) fn event_backing<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ event: v8::Local<'_, v8::Object>,
+) -> v8::Local<'s, v8::Object> {
+ let event = v8::Local::new(scope, event);
+ crate::util::get_private_object(scope, event, EVENT_BACKING_SLOT).unwrap_or(event)
+}
+
+/// A projected Event has its own prototype and expandos, but all its views
+/// observe the same dispatch, cancellation and propagation flags.
+pub(in crate::context_bootstrap) fn bind_event_backing<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+ event: v8::Local<'s, v8::Object>,
+) {
+ set_private_value(scope, wrapper, EVENT_BACKING_SLOT, event.into());
+ for property in [
+ "type",
+ "target",
+ "srcElement",
+ "currentTarget",
+ "eventPhase",
+ "bubbles",
+ "cancelable",
+ "defaultPrevented",
+ "composed",
+ "info",
+ ] {
+ if property == "info"
+ && event.has_own_property(scope, v8str(scope, property).into()) != Some(true)
+ {
+ continue;
+ }
+ let getter = v8::Function::builder(shared_event_attribute_getter)
+ .data(v8str(scope, property).into())
+ .build(scope)
+ .expect("event attribute getter");
+ crate::definitions::define_get_set_property(
+ scope,
+ wrapper,
+ v8str(scope, property).into(),
+ getter.into(),
+ v8::undefined(scope).into(),
+ v8::PropertyAttribute::NONE,
+ "shared Event attribute",
+ )
+ .expect("shared Event attribute");
+ }
+}
+
+fn shared_event_attribute_getter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let wrapper = args.this();
+ let property = args.data().to_rust_string_lossy(scope);
+ let value = shared_event_attribute_value(scope, wrapper, &property);
+ rv.set(value.unwrap_or_else(|| v8::undefined(scope).into()));
+}
+
+fn shared_event_attribute_value<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+ property: &str,
+) -> Option<v8::Local<'s, v8::Value>> {
+ let event = event_backing(scope, wrapper);
+ let key = v8_string(scope, property)?;
+ let value = event.get(scope, key.into())?;
+ if matches!(property, "target" | "srcElement" | "currentTarget")
+ && let Ok(target) = v8::Local::<v8::Object>::try_from(value)
+ && let Some(context) = wrapper.get_creation_context(scope)
+ {
+ return Some(
+ crate::context_bootstrap::shared_event_targets::target_in_realm(scope, target, context)
+ .into(),
+ );
+ }
+ Some(value)
+}
#[derive(WebApiObject)]
#[webapi(plain, data_properties, enumerable)]
@@ -131,6 +213,7 @@ pub(crate) fn event_initialized<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
) -> Option<bool> {
+ let event = event_backing(scope, event);
get_private_value(scope, event, EVENT_INITIALIZED_SLOT).map(|value| value.boolean_value(scope))
}
@@ -152,6 +235,7 @@ pub(in crate::context_bootstrap) fn set_event_dispatch_fields<'s>(
target: v8::Local<'s, v8::Object>,
event: v8::Local<'s, v8::Object>,
) {
+ let event = event_backing(scope, event);
let _ = event.set(scope, v8str(scope, "target").into(), target.into());
let _ = event.set(scope, v8str(scope, "srcElement").into(), target.into());
let _ = event.set(scope, v8str(scope, "currentTarget").into(), target.into());
@@ -167,6 +251,7 @@ pub(in crate::context_bootstrap) fn clear_event_dispatch_fields(
scope: &mut v8::PinScope<'_, '_>,
event: v8::Local<'_, v8::Object>,
) {
+ let event = event_backing(scope, event);
let _ = event.set(
scope,
v8str(scope, "currentTarget").into(),
@@ -185,6 +270,7 @@ pub(crate) fn event_internal_bool_flag<'s>(
event: v8::Local<'s, v8::Object>,
key: &'static str,
) -> bool {
+ let event = event_backing(scope, event);
get_private_value(scope, event, key).is_some_and(|value| value.is_true())
}
@@ -194,6 +280,7 @@ pub(crate) fn set_event_internal_flag(
key: &'static str,
value: bool,
) {
+ let event = event_backing(scope, event);
set_private_value(scope, event, key, v8::Boolean::new(scope, value).into());
}
@@ -201,6 +288,15 @@ pub(crate) fn event_composed_path_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
) -> v8::Local<'s, v8::Value> {
+ let backing = event_backing(scope, event);
+ if !backing.strict_equals(event.into()) {
+ let target = event.get(scope, v8str(scope, "target").into());
+ return if event_is_dispatching(scope, backing) {
+ v8::Array::new_with_elements(scope, &target.into_iter().collect::<Vec<_>>()).into()
+ } else {
+ v8::Array::new(scope, 0).into()
+ };
+ }
get_private_value(scope, event, EVENT_COMPOSED_PATH_SLOT)
.unwrap_or_else(|| v8::Array::new(scope, 0).into())
}
@@ -210,6 +306,7 @@ pub(crate) fn set_event_composed_path<'s>(
event: v8::Local<'s, v8::Object>,
path: v8::Local<'s, v8::Array>,
) {
+ let event = event_backing(scope, event);
set_private_value(scope, event, EVENT_COMPOSED_PATH_SLOT, path.into());
}
@@ -234,10 +331,11 @@ fn event_is_trusted_getter_function<'s>(
rv.set(v8::Boolean::new(scope, trusted).into());
}
-pub(super) fn event_trusted<'s>(
+pub(in crate::context_bootstrap) fn event_trusted<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
) -> bool {
+ let event = event_backing(scope, event);
get_private_value(scope, event, EVENT_TRUSTED_PRIVATE_SLOT)
.map(|value| value.boolean_value(scope))
.unwrap_or(false)
@@ -255,6 +353,7 @@ pub(crate) fn set_event_trusted(
event: v8::Local<'_, v8::Object>,
trusted: bool,
) {
+ let event = event_backing(scope, event);
set_private_value(
scope,
event,
@@ -271,6 +370,7 @@ pub(super) fn event_time_stamp<'s>(
scope: &mut v8::PinScope<'s, '_>,
event: v8::Local<'s, v8::Object>,
) -> f64 {
+ let event = event_backing(scope, event);
get_private_value(scope, event, EVENT_TIMESTAMP_PRIVATE_SLOT)
.and_then(|value| value.number_value(scope))
.or_else(|| {
@@ -379,6 +479,13 @@ fn event_core_attribute_getter<'s>(
return;
}
+ let backing = event_backing(scope, receiver);
+ if !backing.strict_equals(receiver.into()) {
+ let value = shared_event_attribute_value(scope, receiver, key);
+ rv.set(value.unwrap_or_else(|| v8::undefined(scope).into()));
+ return;
+ }
+
let key = v8str(scope, key);
let value = receiver
.get_own_property_descriptor(scope, key.into())
diff --git a/moli-renderer-v8/src/context_bootstrap/events/methods.rs b/moli-renderer-v8/src/context_bootstrap/events/methods.rs
index 64fa35cb8..bef8e4cea 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/methods.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/methods.rs
@@ -4,6 +4,7 @@ pub(in crate::context_bootstrap) fn set_event_default_prevented(
scope: &mut v8::PinScope<'_, '_>,
event: v8::Local<'_, v8::Object>,
) {
+ let event = super::base::event_backing(scope, event);
let key = v8str(scope, "defaultPrevented");
let value = v8::Boolean::new(scope, true).into();
let _ = event.define_own_property(scope, key.into(), value, Default::default());
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
index b5cf2fc3f..de0cb8a69 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses.rs
@@ -14,7 +14,9 @@ mod pointer;
pub(in crate::context_bootstrap::events) use basic::initialize_text_event;
pub(in crate::context_bootstrap) use constructor::build_event_subclass_template;
-pub(in crate::context_bootstrap) use data::run_navigate_event_precommit_handlers;
+pub(in crate::context_bootstrap) use data::{
+ navigation_precommit_controller_for_event, run_navigate_event_precommit_handlers,
+};
pub(in crate::context_bootstrap) use pointer::{
pointer_event_get_coalesced_events_callback, pointer_event_get_predicted_events_callback,
};
diff --git a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
index b85baabca..04b1c31cc 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/subclasses/data.rs
@@ -39,6 +39,7 @@ const NAVIGATE_EVENT_PRECOMMIT_TRANSITION_TYPE_SLOT: &str =
const NAVIGATE_EVENT_PRECOMMIT_TRANSITION_RESOLVER_SLOT: &str =
"__lmNavigateEventPrecommitTransitionResolver";
const PRECOMMIT_CONTROLLER_EVENT_SLOT: &str = "__lmPrecommitControllerEvent";
+const PRECOMMIT_CONTROLLER_BACKING_SLOT: &str = "__moliPrecommitControllerBacking";
const PRECOMMIT_CONTROLLER_ACTIVE_SLOT: &str = "__lmPrecommitControllerActive";
#[derive(Clone, Copy, Default, webidl::WebIdlEnum)]
@@ -905,6 +906,8 @@ fn navigate_event_intercept_callback<'s>(
navigate_event_throw_synthetic_security_error(scope);
return;
};
+ let view = event;
+ let event = crate::context_bootstrap::events::event_backing(scope, view);
let options = match webidl::parse_dictionary::<NavigationInterceptOptionsMembers>(
scope,
args.get(0),
@@ -951,7 +954,7 @@ fn navigate_event_intercept_callback<'s>(
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_PRECOMMIT_SEEN_SLOT, true);
if push_navigation_handler(
scope,
- event,
+ view,
NAVIGATE_EVENT_PRECOMMIT_HANDLERS_SLOT,
precommit_handler,
)
@@ -964,7 +967,7 @@ fn navigate_event_intercept_callback<'s>(
// This is the final intercept step. A failed residence write leaves a
// JavaScript exception pending as this callback returns.
let _residence =
- push_navigation_handler(scope, event, NAVIGATE_EVENT_DEFERRED_HANDLERS_SLOT, handler);
+ push_navigation_handler(scope, view, NAVIGATE_EVENT_DEFERRED_HANDLERS_SLOT, handler);
}
}
@@ -1079,7 +1082,10 @@ fn precommit_controller_event<'s>(
data: v8::Local<'s, v8::Value>,
) -> Option<v8::Local<'s, v8::Object>> {
let controller = v8::Local::<v8::Object>::try_from(data).ok()?;
- if !get_private_value(scope, controller, PRECOMMIT_CONTROLLER_ACTIVE_SLOT)
+ let backing =
+ crate::util::get_private_object(scope, controller, PRECOMMIT_CONTROLLER_BACKING_SLOT)
+ .unwrap_or(controller);
+ if !get_private_value(scope, backing, PRECOMMIT_CONTROLLER_ACTIVE_SLOT)
.is_some_and(|value| value.is_true())
{
navigate_event_throw_invalid_state(scope);
@@ -1094,6 +1100,31 @@ fn precommit_controller_event<'s>(
Some(event)
}
+pub(in crate::context_bootstrap) fn navigation_precommit_controller_for_event<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ argument: v8::Local<'s, v8::Value>,
+ view: v8::Local<'s, v8::Object>,
+) -> v8::Local<'s, v8::Value> {
+ let Ok(controller) = v8::Local::<v8::Object>::try_from(argument) else {
+ return argument;
+ };
+ if get_private_value(scope, controller, PRECOMMIT_CONTROLLER_EVENT_SLOT).is_none() {
+ return argument;
+ }
+ let Some(context) = view.get_creation_context(scope) else {
+ return argument;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let wrapper = create_precommit_controller(scope, view);
+ set_private_value(
+ scope,
+ wrapper,
+ PRECOMMIT_CONTROLLER_BACKING_SLOT,
+ controller.into(),
+ );
+ wrapper.into()
+}
+
fn precommit_controller_add_handler_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -1127,6 +1158,7 @@ fn precommit_controller_redirect_callback<'s>(
let Some(event) = precommit_controller_event(scope, args.data()) else {
return;
};
+ let event = crate::context_bootstrap::events::event_backing(scope, event);
let navigation_type = event
.get(scope, v8str(scope, "navigationType").into())
.and_then(|value| value.to_string(scope))
@@ -1241,6 +1273,7 @@ fn navigate_event_defer_page_swap_callback<'s>(
navigate_event_throw_synthetic_security_error(scope);
return;
};
+ let event = crate::context_bootstrap::events::event_backing(scope, event);
if !navigate_event_can_use_navigation_api(scope, event) {
navigate_event_throw_synthetic_security_error(scope);
return;
@@ -1259,6 +1292,7 @@ fn navigate_event_scroll_callback<'s>(
navigate_event_throw_synthetic_security_error(scope);
return;
};
+ let event = crate::context_bootstrap::events::event_backing(scope, event);
if !navigate_event_can_use_navigation_api(scope, event) {
navigate_event_throw_synthetic_security_error(scope);
return;
diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
index d65001644..064a103c4 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs
@@ -110,15 +110,6 @@ fn mutate_history_object<'s>(
let Some(snapshot) = serialize_history_state(scope, parsed.state) else {
return;
};
- // Argument conversion/serialization belongs to the caller. Entry objects
- // and navigation events belong to the Window, regardless of the caller's world.
- let Some(context) = owner.get_creation_context(scope) else {
- return;
- };
- let scope = &mut v8::ContextScope::new(scope, context);
- let Some(state) = deserialize_history_state(scope, &snapshot) else {
- return;
- };
let Some(location) = window_location_for_holder(scope, owner) else {
return;
};
@@ -158,6 +149,16 @@ fn mutate_history_object<'s>(
return;
}
+ // Web IDL conversion, serialization and URL validation must create errors in
+ // the binding's realm. Only the Window's commit/dispatch machinery runs in
+ // its owning context; listeners enter their own callback realms.
+ let Some(context) = owner.get_creation_context(scope) else {
+ return;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let Some(state) = deserialize_history_state(scope, &snapshot) else {
+ return;
+ };
let mut navigate_outcome = None;
if let Some(navigation) = window_navigation_for_holder(scope, owner) {
let _ = cancel_active_navigation_event(scope, navigation);
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
index 3844fa9c1..001ba8d7c 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/native.rs
@@ -17,7 +17,8 @@ const ENTRY_WRAPPERS: &str = "__moliNavigationEntryWrappers";
struct NativeRecords {
next_id: u64,
histories: HashMap<u64, (v8::Weak<v8::Object>, HistoryRef)>,
- entries: HashMap<u64, (v8::Weak<v8::Object>, HistoryEntryRef)>,
+ entries: HashMap<u64, (Rc<v8::Weak<v8::Object>>, HistoryEntryRef)>,
+ entry_ids: HashMap<usize, Vec<u64>>,
}
fn store(scope: &mut v8::PinScope<'_, '_>) -> Store {
@@ -95,17 +96,34 @@ pub(in crate::context_bootstrap) fn bind_entry<'s>(
) {
let store = store(scope);
let id = next_id(&store);
+ let record_key = Rc::as_ptr(&entry) as usize;
let weak_store = Rc::downgrade(&store);
let weak = v8::Weak::with_finalizer(
scope,
wrapper,
Box::new(move |_| {
if let Some(store) = weak_store.upgrade() {
- store.borrow_mut().entries.remove(&id);
+ let mut records = store.borrow_mut();
+ records.entries.remove(&id);
+ if let Some(ids) = records.entry_ids.get_mut(&record_key) {
+ ids.retain(|candidate| *candidate != id);
+ if ids.is_empty() {
+ records.entry_ids.remove(&record_key);
+ }
+ }
}
}),
);
- store.borrow_mut().entries.insert(id, (weak, entry));
+ store
+ .borrow_mut()
+ .entries
+ .insert(id, (Rc::new(weak), entry));
+ store
+ .borrow_mut()
+ .entry_ids
+ .entry(record_key)
+ .or_default()
+ .push(id);
set_private_value(
scope,
wrapper,
@@ -127,6 +145,74 @@ pub(in crate::context_bootstrap) fn entry<'s>(
.map(|(_, record)| record.clone())
}
+/// V8 wrappers are world-local, while their record and event target are shared.
+/// Weak handles preserve identity for observable wrappers without retaining a
+/// destroyed isolated realm from the Window's canonical wrapper cache.
+pub(in crate::context_bootstrap) fn entry_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ source: v8::Local<'s, v8::Object>,
+ context: v8::Local<'s, v8::Context>,
+) -> v8::Local<'s, v8::Object> {
+ if source.get_creation_context(scope) == Some(context) {
+ return source;
+ }
+ let Some(record) = entry(scope, source) else {
+ return source;
+ };
+ let registry = store(scope);
+ let candidates: Vec<_> = {
+ let records = registry.borrow();
+ records
+ .entry_ids
+ .get(&(Rc::as_ptr(&record) as usize))
+ .into_iter()
+ .flatten()
+ .filter_map(|id| records.entries.get(id))
+ .map(|(wrapper, _)| wrapper.clone())
+ .collect()
+ };
+ for candidate in candidates {
+ if let Some(wrapper) = candidate.to_local(scope)
+ && wrapper.get_creation_context(scope) == Some(context)
+ {
+ return wrapper;
+ }
+ }
+ let owner = super::super::navigation_window::runtime_window_owner(scope, source);
+ let target = super::super::shared_event_targets::shared_target_owner(scope, source);
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let wrapper = super::super::navigation_entry::wrap_native_navigation_entry(scope, record);
+ super::super::navigation_window::set_runtime_window_owner(scope, wrapper, owner);
+ super::super::shared_event_targets::bind_shared_target(scope, wrapper, target);
+ wrapper
+}
+
+pub(in crate::context_bootstrap) fn same_entry<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ left: v8::Local<'s, v8::Object>,
+ right: v8::Local<'s, v8::Object>,
+) -> bool {
+ left.strict_equals(right.into())
+ || match (entry(scope, left), entry(scope, right)) {
+ (Some(left), Some(right)) => Rc::ptr_eq(&left, &right),
+ _ => false,
+ }
+}
+
+pub(in crate::context_bootstrap) fn entry_value_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: v8::Local<'s, v8::Context>,
+) -> v8::Local<'s, v8::Value> {
+ let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {
+ return value;
+ };
+ if entry(scope, object).is_none() {
+ return value;
+ }
+ entry_in_realm(scope, object, context).into()
+}
+
fn wrappers<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/dispatch.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/dispatch.rs
index 95acda01f..29470ecff 100644
--- a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/dispatch.rs
+++ b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/dispatch.rs
@@ -123,14 +123,31 @@ pub(crate) fn dispatch_simple_event_target_event_collecting_errors<'s>(
continue;
};
set_event_internal_flag(scope, event, EVENT_PASSIVE_SLOT, listener.passive);
+ let callback_target =
+ crate::context_bootstrap::shared_event_targets::target_in_realm(
+ scope,
+ target,
+ listener.relevant_context(),
+ );
+ let Some(callback_event) =
+ crate::context_bootstrap::navigation_event_worlds::event_in_realm(
+ scope,
+ target,
+ event,
+ event_type,
+ listener.relevant_context(),
+ )
+ else {
+ continue;
+ };
let outcome = invoke_simple_event_listener_collecting_errors(
scope,
event_type,
&format!("simple event target {event_type} listener"),
&listener,
- target.into(),
- &[event.into()],
- event,
+ callback_target.into(),
+ &[callback_event.into()],
+ callback_event,
callback_errors.as_deref_mut(),
);
dispatched |= outcome.invoked;
diff --git a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs
index 033d9d9de..2ccbc364f 100644
--- a/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs
+++ b/moli-renderer-v8/src/context_bootstrap/media_queries/events/simple_event_target/listeners.rs
@@ -26,6 +26,7 @@ const SIMPLE_EVENT_TARGET_LISTENER_ABORT_ALGORITHM_SLOT: &str =
"__moliSimpleEventTargetListenerAbortAlgorithm";
const SIMPLE_EVENT_TARGET_LISTENER_TYPE_ORDER_SLOT: &str =
"__moliSimpleEventTargetListenerTypeOrder";
+const HANDLER_TARGET_SLOT: &str = "__moliSimpleEventHandlerTarget";
#[derive(WebApiObject)]
#[webapi(plain)]
@@ -435,6 +436,7 @@ fn simple_object_event_listener_registry<'s>(
slot_name: &str,
create: bool,
) -> Option<v8::Local<'s, v8::Object>> {
+ let target = crate::context_bootstrap::shared_event_targets::shared_target_owner(scope, target);
if let Some(registry) = get_private_object(scope, target, slot_name) {
return Some(registry);
}
@@ -574,6 +576,7 @@ pub(crate) fn simple_object_event_set_ordered_handler<'s>(
};
if simple_object_event_listener_handler_slot(scope, candidate).as_deref()
== Some(handler_slot_name)
+ && handler_belongs_to_target(scope, candidate, target)
{
if let Ok(entry) = v8::Local::<v8::Object>::try_from(candidate) {
set_private_value(
@@ -613,6 +616,7 @@ pub(crate) fn simple_object_event_set_ordered_handler<'s>(
relevant_context_anchor,
incumbent_context_anchor,
);
+ set_private_value(scope, entry, HANDLER_TARGET_SLOT, target.into());
let _ = listeners.set_index(scope, listeners.length(), entry.into());
ensure_simple_object_event_type_order(scope, target, slot_name, event_type);
return;
@@ -625,6 +629,7 @@ pub(crate) fn simple_object_event_set_ordered_handler<'s>(
};
if simple_object_event_listener_handler_slot(scope, candidate).as_deref()
== Some(handler_slot_name)
+ && handler_belongs_to_target(scope, candidate, target)
{
continue;
}
@@ -640,6 +645,17 @@ pub(crate) fn simple_object_event_set_ordered_handler<'s>(
}
}
+fn handler_belongs_to_target<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ candidate: v8::Local<'s, v8::Value>,
+ target: v8::Local<'s, v8::Object>,
+) -> bool {
+ v8::Local::<v8::Object>::try_from(candidate)
+ .ok()
+ .and_then(|entry| get_private_value(scope, entry, HANDLER_TARGET_SLOT))
+ .is_some_and(|owner| owner.strict_equals(target.into()))
+}
+
pub(in crate::context_bootstrap::media_queries::events::simple_event_target) fn simple_event_target_uses_ordered_handlers<
's,
>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
index 808e11ed4..b90c3e2a0 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs
@@ -193,6 +193,13 @@ pub(super) fn create_navigation_activation_object<'s>(
.and_then(|value| v8_string(scope, value))
.map(v8::Local::<v8::Value>::from)
.unwrap_or_else(|| v8::null(scope).into());
+ let context = scope.get_current_context();
+ let entry = super::history_runtime::native::entry_in_realm(scope, entry, context);
+ let from = if let Ok(from) = v8::Local::<v8::Object>::try_from(from) {
+ super::history_runtime::native::entry_in_realm(scope, from, context).into()
+ } else {
+ from
+ };
NavigationActivationObjectDeclaration::new(entry, from, navigation_type)
.bind(scope)
.expect("NavigationActivation declaration should bind")
@@ -206,9 +213,12 @@ pub(super) fn install_navigation_activation_runtime_state<'s>(
activation: Option<&NavigationActivationSeed>,
) {
let activation_value = create_navigation_activation_object(scope, current_entry, activation);
- let transition_value = v8::null(scope).into();
set_navigation_activation_value(scope, navigation, activation_value);
- set_navigation_transition_value(scope, navigation, transition_value);
+ if super::shared_event_targets::shared_target_owner(scope, navigation)
+ .strict_equals(navigation.into())
+ {
+ set_navigation_transition_value(scope, navigation, v8::null(scope).into());
+ }
}
pub(super) fn install_navigation_transition<'s>(
@@ -224,6 +234,10 @@ pub(super) fn install_navigation_transition<'s>(
let committed_resolver = v8::PromiseResolver::new(scope)?;
let committed = committed_resolver.get_promise(scope);
suppress_unhandled_rejection(scope, committed);
+ let context = scope.get_current_context();
+ let from = super::history_runtime::native::entry_in_realm(scope, from, context);
+ let to =
+ to.and_then(|to| super::navigation_events::navigation_destination_for_realm(scope, to));
let transition = NavigationTransitionObjectDeclaration {
from,
to: to
@@ -246,6 +260,11 @@ pub(super) fn resolve_navigation_transition_committed<'s>(
value: v8::Local<'s, v8::Value>,
) {
if let Some(resolver) = take_navigation_transition_committed_resolver(scope, navigation) {
+ let context = resolver
+ .get_promise(scope)
+ .get_creation_context(scope)
+ .unwrap_or_else(|| scope.get_current_context());
+ let value = super::history_runtime::native::entry_value_in_realm(scope, value, context);
let _ = resolver.resolve(scope, value);
}
}
@@ -366,7 +385,9 @@ pub(super) fn navigation_current_entry_value<'s>(
navigation: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Value>> {
let owner = runtime_window_owner(scope, navigation);
- super::navigation_entry::navigation_current_entry(scope, owner).map(Into::into)
+ let entry = super::navigation_entry::navigation_current_entry(scope, owner)?;
+ let context = navigation.get_creation_context(scope)?;
+ Some(super::history_runtime::native::entry_in_realm(scope, entry, context).into())
}
pub(super) fn navigation_activation_value<'s>(
@@ -381,15 +402,20 @@ pub(super) fn navigation_transition_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Value>> {
- get_private_value(scope, navigation, NAVIGATION_TRANSITION_SLOT)
- .filter(|value| !value.is_undefined())
+ let context = navigation.get_creation_context(scope)?;
+ let Some(transition) = navigation_transition_object(scope, navigation) else {
+ return Some(v8::null(scope).into());
+ };
+ super::navigation_transition_worlds::transition_in_realm(scope, transition, context)
+ .map(Into::into)
}
fn navigation_transition_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Object>> {
- navigation_transition_value(scope, navigation)
+ let navigation = super::shared_event_targets::shared_target_owner(scope, navigation);
+ get_private_value(scope, navigation, NAVIGATION_TRANSITION_SLOT)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
}
@@ -406,6 +432,7 @@ fn set_navigation_transition_value<'s>(
navigation: v8::Local<'s, v8::Object>,
value: v8::Local<'s, v8::Value>,
) {
+ let navigation = super::shared_event_targets::shared_target_owner(scope, navigation);
set_private_value(scope, navigation, NAVIGATION_TRANSITION_SLOT, value);
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
index ca934c736..9c2fd76f1 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_callbacks/navigation.rs
@@ -69,6 +69,19 @@ pub(in crate::context_bootstrap) fn navigation_entries_callback<'s>(
};
let current_entry = navigation_current_entry(scope, owner);
let copied = build_visible_navigation_entries_array(scope, entries, current_entry);
+ let context = navigation
+ .get_creation_context(scope)
+ .unwrap_or_else(|| scope.get_current_context());
+ for index in 0..copied.length() {
+ if let Some(entry) = copied
+ .get_index(scope, index)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ {
+ let wrapper =
+ super::super::history_runtime::native::entry_in_realm(scope, entry, context);
+ let _ = copied.set_index(scope, index, wrapper.into());
+ }
+ }
rv.set(copied.into());
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
index 842051de3..47bbf6b90 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
@@ -165,6 +165,7 @@ pub(in crate::context_bootstrap) fn wrap_native_navigation_entry<'s>(
NAVIGATION_ENTRY_EVENT_LISTENERS_SLOT,
false,
);
+ super::shared_event_targets::install_handlers(scope, entry, true);
entry
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs
new file mode 100644
index 000000000..855c4372a
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_event_worlds.rs
@@ -0,0 +1,97 @@
+//! Event views for one Navigation dispatch. User callbacks never receive the
+//! internal control object, so page expandos cannot cross into another world.
+
+use super::{events, history_runtime::native, shared_event_targets};
+use crate::util::{get_private_value, set_private_value, v8str};
+
+const WRAPPERS: &str = "__moliNavigationEventWrappers";
+
+pub(super) fn event_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+ event: v8::Local<'s, v8::Object>,
+ event_type: &str,
+ context: v8::Local<'s, v8::Context>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ // Script-created events retain their dispatchEvent identity. This adapter
+ // handles the UA events belonging to the shared Navigation transaction.
+ if !shared_event_targets::is_shared_target(scope, target)
+ || !events::event_trusted(scope, event)
+ {
+ return Some(event);
+ }
+ let target = shared_event_targets::target_in_realm(scope, target, context);
+ // A callback in another same-world Document still receives the owning
+ // Window's wrapper. Its callback realm is entered separately by the invoker.
+ let context = target.get_creation_context(scope).unwrap_or(context);
+ let wrappers = get_private_value(scope, event, WRAPPERS)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ .unwrap_or_else(|| {
+ let map = v8::Map::new(scope);
+ set_private_value(scope, event, WRAPPERS, map.into());
+ map
+ });
+ let global = context.global(scope);
+ if let Some(wrapper) = wrappers
+ .get(scope, global.into())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ {
+ return Some(wrapper);
+ }
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let init = crate::util::new_null_prototype_object(scope);
+ let (interface, properties): (&str, &[&'static str]) = match event_type {
+ "navigate" => (
+ "NavigateEvent",
+ &[
+ "navigationType",
+ "destination",
+ "canIntercept",
+ "userInitiated",
+ "hashChange",
+ "signal",
+ "formData",
+ "downloadRequest",
+ "info",
+ "sourceElement",
+ "hasUAVisualTransition",
+ ],
+ ),
+ "currententrychange" => (
+ "NavigationCurrentEntryChangeEvent",
+ &["from", "navigationType"],
+ ),
+ "navigateerror" => (
+ "ErrorEvent",
+ &["message", "filename", "lineno", "colno", "error"],
+ ),
+ _ => ("Event", &[]),
+ };
+ for property in properties
+ .iter()
+ .copied()
+ .chain(["bubbles", "cancelable", "composed"])
+ {
+ let mut value = event.get(scope, v8str(scope, property).into())?;
+ if property == "from" {
+ if let Ok(entry) = v8::Local::<v8::Object>::try_from(value) {
+ value = native::entry_in_realm(scope, entry, context).into();
+ }
+ } else if property == "destination" {
+ let destination = v8::Local::<v8::Object>::try_from(value).ok()?;
+ value = super::navigation_events::navigation_destination_for_realm(scope, destination)?
+ .into();
+ }
+ let _ = init.set(scope, v8str(scope, property).into(), value);
+ }
+ let constructor =
+ super::exposed_interfaces::ensure_intrinsic_interface_constructor(scope, interface).ok()?;
+ let event_type = crate::util::v8_string(scope, event_type)?;
+ let wrapper = constructor.new_instance(scope, &[event_type.into(), init.into()])?;
+ for property in ["target", "srcElement"] {
+ let _ = wrapper.set(scope, v8str(scope, property).into(), target.into());
+ }
+ events::bind_event_backing(scope, wrapper, event);
+ let _ = wrappers.set(scope, global.into(), wrapper.into());
+ Some(wrapper)
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
index 251444c67..e00c4b72b 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
@@ -32,6 +32,8 @@ use moli_webapi_declare::WebApiObject;
const NAVIGATION_DESTINATION_STATE_SLOT: &str = "__lmNavigationDestinationState";
const NAVIGATION_DESTINATION_ENTRY_SLOT: &str = "__lmNavigationDestinationEntry";
+const NAVIGATION_DESTINATION_BACKING_SLOT: &str = "__moliNavigationDestinationBacking";
+const NAVIGATION_DESTINATION_WRAPPERS_SLOT: &str = "__moliNavigationDestinationWrappers";
const NAVIGATION_TRACKED_DESTINATIONS_SLOT: &str = "__lmNavigationTrackedDestinations";
const NAVIGATE_EVENT_SYNTHETIC_SLOT: &str = "__lmNavigateEventSynthetic";
const NAVIGATE_EVENT_INTERCEPTED_SLOT: &str = "__lmNavigateEventIntercepted";
@@ -930,6 +932,7 @@ pub(super) fn dispatch_navigation_navigate_event_with_form_data_and_outcome<'s>(
else {
return NavigationDispatchOutcome::proceed();
};
+ mark_event_trusted(scope, event);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_SYNTHETIC_SLOT, false);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_FOCUS_RESET_SLOT, true);
set_navigate_event_private_bool(
@@ -1176,6 +1179,7 @@ fn dispatch_cross_document_navigation_navigate_event_for_window_with_type_form_d
else {
return true;
};
+ mark_event_trusted(scope, event);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_SYNTHETIC_SLOT, false);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_FOCUS_RESET_SLOT, true);
set_navigate_event_private_bool(
@@ -1271,6 +1275,7 @@ pub(super) fn dispatch_navigation_traverse_event_with_outcome<'s>(
else {
return NavigationDispatchOutcome::proceed();
};
+ mark_event_trusted(scope, event);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_SYNTHETIC_SLOT, false);
set_navigate_event_private_bool(scope, event, NAVIGATE_EVENT_FOCUS_RESET_SLOT, true);
set_navigate_event_private_bool(
@@ -1357,6 +1362,75 @@ fn create_navigation_destination<'s>(
.expect("NavigationDestination declaration should bind")
}
+pub(super) fn navigation_destination_for_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ destination: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let destination =
+ crate::util::get_private_object(scope, destination, NAVIGATION_DESTINATION_BACKING_SLOT)
+ .unwrap_or(destination);
+ let global = scope.get_current_context().global(scope);
+ let wrappers = get_private_value(scope, destination, NAVIGATION_DESTINATION_WRAPPERS_SLOT)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ .unwrap_or_else(|| {
+ let map = v8::Map::new(scope);
+ set_private_value(
+ scope,
+ destination,
+ NAVIGATION_DESTINATION_WRAPPERS_SLOT,
+ map.into(),
+ );
+ map
+ });
+ if let Some(wrapper) = wrappers
+ .get(scope, global.into())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ {
+ return Some(wrapper);
+ }
+ let wrapper = create_navigation_destination(scope, "", false, -1, None);
+ set_private_value(
+ scope,
+ wrapper,
+ NAVIGATION_DESTINATION_BACKING_SLOT,
+ destination.into(),
+ );
+ for property in ["url", "key", "id", "index", "sameDocument"] {
+ let getter = v8::Function::builder(navigation_destination_view_getter)
+ .data(v8str(scope, property).into())
+ .build(scope)?;
+ crate::definitions::define_get_set_property(
+ scope,
+ wrapper,
+ v8str(scope, property).into(),
+ getter.into(),
+ v8::undefined(scope).into(),
+ v8::PropertyAttribute::NONE,
+ "NavigationDestination view",
+ )
+ .ok()?;
+ }
+ let _ = wrappers.set(scope, global.into(), wrapper.into());
+ Some(wrapper)
+}
+
+fn navigation_destination_view_getter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(backing) =
+ crate::util::get_private_object(scope, args.this(), NAVIGATION_DESTINATION_BACKING_SLOT)
+ else {
+ return;
+ };
+ if let Some(key) = args.data().to_string(scope)
+ && let Some(value) = backing.get(scope, key.into())
+ {
+ rv.set(value);
+ }
+}
+
fn create_navigation_destination_for_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
@@ -1467,6 +1541,9 @@ fn navigation_destination_state<'s>(
scope: &mut v8::PinScope<'s, '_>,
destination: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Value>> {
+ let destination =
+ crate::util::get_private_object(scope, destination, NAVIGATION_DESTINATION_BACKING_SLOT)
+ .unwrap_or(destination);
get_private_value(scope, destination, NAVIGATION_DESTINATION_STATE_SLOT)
.filter(|value| !value.is_undefined())
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs b/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
index d281ed19d..90564d7ff 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_handler_callbacks.rs
@@ -35,6 +35,7 @@ pub(in crate::context_bootstrap) const NAVIGATE_EVENT_DEFERRED_HANDLERS_SLOT: &s
"__lmNavigateEventDeferredHandlers";
pub(in crate::context_bootstrap) const NAVIGATE_EVENT_ADDED_HANDLERS_SLOT: &str =
"__lmNavigateEventAddedHandlers";
+const HANDLER_EVENT_VIEW_SLOT: &str = "__moliNavigationHandlerEventView";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::context_bootstrap) enum NavigationHandlerResidenceFailure {
@@ -54,6 +55,8 @@ pub(in crate::context_bootstrap) fn push_navigation_handler<'s>(
callback: WebIdlCallbackFunction,
) -> Result<(), NavigationHandlerResidenceFailure> {
let callback = V8TracedWindowWebIdlCallbackFunction::new(scope, callback).into_object();
+ set_private_value(scope, callback, HANDLER_EVENT_VIEW_SLOT, event.into());
+ let event = super::events::event_backing(scope, event);
let handlers = get_private_value(scope, event, slot)
.and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
.unwrap_or_else(|| {
@@ -178,13 +181,21 @@ fn invoke_navigation_handler<'s>(
carrier: v8::Local<'s, v8::Object>,
arguments: &[v8::Local<'s, v8::Value>],
) -> Result<v8::Local<'s, v8::Value>, v8::Local<'s, v8::Value>> {
+ let view =
+ crate::util::get_private_object(scope, carrier, HANDLER_EVENT_VIEW_SLOT).unwrap_or(event);
+ let arguments: Vec<_> = arguments
+ .iter()
+ .map(|argument| {
+ super::events::navigation_precommit_controller_for_event(scope, *argument, view)
+ })
+ .collect();
let callback = V8TracedWindowWebIdlCallbackFunction::from_object(carrier)
.prepare(scope, unsafe { &*host_ptr });
match callback.invoke(
scope,
unsafe { &*host_ptr },
- event.into(),
- arguments,
+ view.into(),
+ &arguments,
|scope, callback, receiver, arguments| {
let try_catch = std::pin::pin!(v8::TryCatch::new(scope));
let mut scope = try_catch.init();
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_lifecycle.rs b/moli-renderer-v8/src/context_bootstrap/navigation_lifecycle.rs
index d4408a4d7..c6b3ef543 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_lifecycle.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_lifecycle.rs
@@ -119,8 +119,7 @@ pub(super) fn settle_navigation_committed<'s>(
resolve: v8::Local<'s, v8::Function>,
value: v8::Local<'s, v8::Value>,
) {
- let receiver = v8::undefined(scope).into();
- let _ = resolve.call(scope, receiver, &[value]);
+ settle_navigation_finished_resolved_immediately(scope, resolve, value);
resolve_navigation_transition_committed(scope, navigation, value);
}
@@ -129,6 +128,10 @@ pub(super) fn settle_navigation_finished_resolved_immediately<'s>(
resolve: v8::Local<'s, v8::Function>,
value: v8::Local<'s, v8::Value>,
) {
+ let context = resolve
+ .get_creation_context(scope)
+ .unwrap_or_else(|| scope.get_current_context());
+ let value = super::history_runtime::native::entry_value_in_realm(scope, value, context);
let receiver = v8::undefined(scope).into();
let _ = resolve.call(scope, receiver, &[value]);
}
@@ -285,8 +288,7 @@ fn schedule_navigation_finished_resolve<'s>(
.data(data.into())
.build(scope)
else {
- let receiver = v8::undefined(scope).into();
- let _ = resolve.call(scope, receiver, &[value]);
+ settle_navigation_finished_resolved_immediately(scope, resolve, value);
return;
};
enqueue_navigation_lifecycle_microtask(scope, callback);
@@ -307,8 +309,7 @@ fn navigation_finished_resolve_callback<'s>(
};
let value = get_private_value(scope, data, NAVIGATION_FINISH_VALUE_SLOT)
.unwrap_or_else(|| v8::undefined(scope).into());
- let receiver = v8::undefined(scope).into();
- let _ = resolve.call(scope, receiver, &[value]);
+ settle_navigation_finished_resolved_immediately(scope, resolve, value);
}
fn navigation_finished_reject_callback<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs b/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
index 9a3f816a2..e9b3b2f5b 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_projection.rs
@@ -32,7 +32,7 @@ pub(super) fn visible_navigation_index_for_entry<'s>(
) -> Option<u32> {
visible_navigation_entries(scope, entries, current_entry)
.into_iter()
- .position(|entry| entry.strict_equals(target_entry.into()))
+ .position(|entry| super::history_runtime::native::same_entry(scope, entry, target_entry))
.map(|index| index as u32)
}
@@ -114,7 +114,7 @@ fn entry_is_hidden_for_owner<'s>(
if !runtime_window_owner(scope, entry).strict_equals(owner.into()) {
return true;
}
- !entry.strict_equals(current_entry.into())
+ !super::history_runtime::native::same_entry(scope, entry, current_entry)
&& navigation_entry_url_value(scope, entry)
.is_some_and(|url| url.split('#').next() == Some("about:blank"))
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_result.rs b/moli-renderer-v8/src/context_bootstrap/navigation_result.rs
index bc8553305..cb863830e 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_result.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_result.rs
@@ -479,6 +479,9 @@ pub(super) fn navigation_immediate_result_with_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
resolved_value: v8::Local<'s, v8::Value>,
) -> v8::Local<'s, v8::Object> {
+ let context = scope.get_current_context();
+ let resolved_value =
+ super::history_runtime::native::entry_value_in_realm(scope, resolved_value, context);
let Some(committed_resolver) = v8::PromiseResolver::new(scope) else {
return navigation_result_fallback_object(scope);
};
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs
index b9b310faa..88de1a94e 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs
@@ -107,6 +107,14 @@ pub(in crate::context_bootstrap) fn build_navigation_runtime_state<'s>(
NAVIGATION_EVENT_LISTENERS_SLOT,
false,
);
+ super::super::shared_event_targets::install_handlers(scope, navigation, false);
+ let owner = history_window_owner(scope, window);
+ if window_has_shared_history(scope, window)
+ && let Some(canonical) =
+ super::super::navigation_window::window_navigation_for_holder(scope, owner)
+ {
+ super::super::shared_event_targets::bind_shared_target(scope, navigation, canonical);
+ }
install_navigation_activation_runtime_state(
scope,
navigation,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs b/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs
new file mode 100644
index 000000000..5f18ffb80
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_transition_worlds.rs
@@ -0,0 +1,117 @@
+use super::history_runtime::native;
+use crate::util::{get_private_value, set_private_value, v8str};
+use crate::web_api_interfaces;
+use moli_webapi_declare::WebApiObject;
+
+const WRAPPERS: &str = "__moliNavigationTransitionWrappers";
+
+#[derive(WebApiObject)]
+#[webapi(interface = web_api_interfaces::NavigationTransition, own_to_string_tag = "NavigationTransition", readonly_to_string_tag)]
+struct TransitionView<'scope> {
+ #[webapi(data_property)]
+ from: v8::Local<'scope, v8::Value>,
+ #[webapi(data_property)]
+ to: v8::Local<'scope, v8::Value>,
+ #[webapi(data_property)]
+ navigation_type: v8::Local<'scope, v8::Value>,
+ #[webapi(data_property)]
+ committed: v8::Local<'scope, v8::Promise>,
+ #[webapi(data_property)]
+ finished: v8::Local<'scope, v8::Promise>,
+}
+
+pub(super) fn transition_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ transition: v8::Local<'s, v8::Object>,
+ context: v8::Local<'s, v8::Context>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ let global = context.global(scope);
+ let wrappers = get_private_value(scope, transition, WRAPPERS)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ .unwrap_or_else(|| {
+ let map = v8::Map::new(scope);
+ set_private_value(scope, transition, WRAPPERS, map.into());
+ map
+ });
+ if let Some(wrapper) = wrappers
+ .get(scope, global.into())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ {
+ return Some(wrapper);
+ }
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let from = transition.get(scope, v8str(scope, "from").into())?;
+ let from = native::entry_value_in_realm(scope, from, context);
+ let to = transition.get(scope, v8str(scope, "to").into())?;
+ let to = if let Ok(to) = v8::Local::<v8::Object>::try_from(to) {
+ super::navigation_events::navigation_destination_for_realm(scope, to)?.into()
+ } else {
+ to
+ };
+ let navigation_type = transition.get(scope, v8str(scope, "navigationType").into())?;
+ let committed = transition.get(scope, v8str(scope, "committed").into())?;
+ let committed =
+ promise_in_current_realm(scope, v8::Local::<v8::Promise>::try_from(committed).ok()?)?;
+ let finished = transition.get(scope, v8str(scope, "finished").into())?;
+ let finished =
+ promise_in_current_realm(scope, v8::Local::<v8::Promise>::try_from(finished).ok()?)?;
+ let wrapper = TransitionView {
+ from,
+ to,
+ navigation_type,
+ committed,
+ finished,
+ }
+ .bind(scope)
+ .ok()?;
+ let _ = wrappers.set(scope, global.into(), wrapper.into());
+ Some(wrapper)
+}
+
+fn promise_in_current_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ promise: v8::Local<'s, v8::Promise>,
+) -> Option<v8::Local<'s, v8::Promise>> {
+ let context = scope.get_current_context();
+ if promise.get_creation_context(scope) == Some(context) {
+ return Some(promise);
+ }
+ let resolver = v8::PromiseResolver::new(scope)?;
+ let result = resolver.get_promise(scope);
+ let fulfilled = v8::Function::builder(resolve_promise)
+ .data(resolver.into())
+ .build(scope)?;
+ let rejected = v8::Function::builder(reject_promise)
+ .data(resolver.into())
+ .build(scope)?;
+ let reaction = promise.then2(scope, fulfilled, rejected)?;
+ super::navigation_result::suppress_unhandled_rejection(scope, reaction);
+ super::navigation_result::suppress_unhandled_rejection(scope, result);
+ Some(result)
+}
+
+fn resolve_promise<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Ok(object) = v8::Local::<v8::Object>::try_from(args.data()) else {
+ return;
+ };
+ let resolver = unsafe { v8::Local::<v8::PromiseResolver>::cast_unchecked(object) };
+ let context = scope.get_current_context();
+ let value = native::entry_value_in_realm(scope, args.get(0), context);
+ let _ = resolver.resolve(scope, value);
+}
+
+fn reject_promise<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Ok(object) = v8::Local::<v8::Object>::try_from(args.data()) else {
+ return;
+ };
+ let resolver = unsafe { v8::Local::<v8::PromiseResolver>::cast_unchecked(object) };
+ let _ = resolver.reject(scope, args.get(0));
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs b/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs
new file mode 100644
index 000000000..b749179ba
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/shared_event_targets.rs
@@ -0,0 +1,149 @@
+//! A single listener list behind world-local Navigation and entry wrappers.
+//! The list retains callback realms using the ordinary EventTarget machinery;
+//! dispatch still runs once, with one cancellation/propagation state.
+
+use super::{history_runtime::native, media_queries};
+use crate::util::{get_private_object, get_private_value, set_private_value, v8str};
+
+const OWNER: &str = "__moliSharedEventTargetOwner";
+const WRAPPERS: &str = "__moliSharedEventTargetWrappers";
+const HANDLERS: [(&str, &str); 5] = [
+ ("onnavigate", "navigate"),
+ ("onnavigatesuccess", "navigatesuccess"),
+ ("onnavigateerror", "navigateerror"),
+ ("oncurrententrychange", "currententrychange"),
+ ("ondispose", "dispose"),
+];
+
+pub(super) fn is_shared_target<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+) -> bool {
+ get_private_object(scope, target, OWNER).is_some()
+}
+
+pub(super) fn shared_target_owner<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+) -> v8::Local<'s, v8::Object> {
+ get_private_object(scope, target, OWNER).unwrap_or(target)
+}
+
+pub(super) fn bind_shared_target<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ wrapper: v8::Local<'s, v8::Object>,
+ owner: v8::Local<'s, v8::Object>,
+) {
+ let owner = shared_target_owner(scope, owner);
+ set_private_value(scope, wrapper, OWNER, owner.into());
+ if native::entry(scope, wrapper).is_none() {
+ let context = wrapper
+ .get_creation_context(scope)
+ .expect("Navigation realm");
+ let global = context.global(scope);
+ let wrappers = get_private_value(scope, global, WRAPPERS)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ .unwrap_or_else(|| {
+ let map = v8::Map::new(scope);
+ set_private_value(scope, global, WRAPPERS, map.into());
+ map
+ });
+ let _ = wrappers.set(scope, owner.into(), wrapper.into());
+ }
+}
+
+pub(super) fn target_in_realm<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+ context: v8::Local<'s, v8::Context>,
+) -> v8::Local<'s, v8::Object> {
+ let Some(owner) = get_private_object(scope, target, OWNER) else {
+ return target;
+ };
+ if native::entry(scope, target).is_some() {
+ let window = super::navigation_window::runtime_window_owner(scope, owner);
+ let navigation = super::navigation_window::window_navigation_for_holder(scope, window);
+ let context = navigation
+ .map(|navigation| target_in_realm(scope, navigation, context))
+ .and_then(|navigation| navigation.get_creation_context(scope))
+ .unwrap_or(context);
+ return native::entry_in_realm(scope, owner, context);
+ }
+ let global = context.global(scope);
+ get_private_value(scope, global, WRAPPERS)
+ .and_then(|value| v8::Local::<v8::Map>::try_from(value).ok())
+ .and_then(|map| map.get(scope, owner.into()))
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ .unwrap_or(target)
+}
+
+pub(super) fn install_handlers<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ target: v8::Local<'s, v8::Object>,
+ entry: bool,
+) {
+ media_queries::install_simple_event_target_ordered_handlers(scope, target);
+ bind_shared_target(scope, target, target);
+ for (index, (property, _)) in HANDLERS.iter().enumerate() {
+ if (*property == "ondispose") != entry {
+ continue;
+ }
+ let data = v8::Integer::new(scope, index as i32);
+ let getter = v8::Function::builder(handler_getter)
+ .data(data.into())
+ .build(scope)
+ .unwrap();
+ let setter = v8::Function::builder(handler_setter)
+ .data(data.into())
+ .build(scope)
+ .unwrap();
+ crate::definitions::define_get_set_property(
+ scope,
+ target,
+ v8str(scope, property).into(),
+ getter.into(),
+ setter.into(),
+ v8::PropertyAttribute::NONE,
+ "Navigation event handler",
+ )
+ .expect("Navigation handler accessor");
+ }
+}
+
+fn handler_getter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let index = args.data().int32_value(scope).unwrap_or(-1) as usize;
+ if let Some((slot, _)) = HANDLERS.get(index) {
+ rv.set(
+ get_private_value(scope, args.this(), slot).unwrap_or_else(|| v8::null(scope).into()),
+ );
+ }
+}
+
+fn handler_setter<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ let index = args.data().int32_value(scope).unwrap_or(-1) as usize;
+ let Some((slot, event_type)) = HANDLERS.get(index) else {
+ return;
+ };
+ let target = args.this();
+ let active = args.get(0).is_object();
+ let value = if active {
+ args.get(0)
+ } else {
+ v8::null(scope).into()
+ };
+ set_private_value(scope, target, slot, value);
+ let Some(listeners) = media_queries::simple_event_target_slot_name(scope, target) else {
+ return;
+ };
+ media_queries::simple_object_event_set_ordered_handler(
+ scope, target, &listeners, event_type, slot, active,
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
index de2a89ec6..9bc5eab4f 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs
@@ -1,5 +1,330 @@
use super::*;
+#[test]
+fn history_worlds_navigation_entries_keep_their_own_wrappers() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ navigation.updateCurrentEntry({state: {value: 7, map: new Map([['x', 2n]])}});
+ navigation.currentEntry.expando = 'page';
+ navigation.currentEntry.getState = () => 'page-override';
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("entries", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"JSON.stringify([
+ navigation.currentEntry instanceof NavigationHistoryEntry,
+ navigation.currentEntry.expando === undefined,
+ navigation.currentEntry.getState().value,
+ navigation.currentEntry.getState().map instanceof Map,
+ navigation.currentEntry.getState().map.get('x') === 2n,
+ navigation.entries().includes(navigation.currentEntry),
+ navigation.currentEntry.index === navigation.entries().length - 1,
+ navigation.currentEntry === navigation.currentEntry
+ ])"#
+ )
+ .unwrap(),
+ "[true,true,7,true,true,true,true,true]"
+ );
+}
+
+#[test]
+fn history_worlds_navigation_listeners_share_notifications_and_cancellation() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.changes = 0;
+ globalThis.navigates = 0;
+ navigation.addEventListener('currententrychange', () => changes++);
+ navigation.addEventListener('navigate', () => navigates++);
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("events", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ globalThis.changes = 0;
+ navigation.addEventListener('currententrychange', () => changes++);
+ history.pushState({value: 1}, '', '#next');
+ String(changes)
+ "##
+ )
+ .unwrap(),
+ "1"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ const before = location.href;
+ const length = history.length;
+ let seen = 0;
+ navigation.addEventListener('navigate', event => {
+ seen++;
+ event.preventDefault();
+ }, {once: true});
+ history.pushState({}, '', '#should-not-commit');
+ JSON.stringify([seen, location.href === before, history.length === length, changes])
+ "##
+ )
+ .unwrap(),
+ "[1,true,true,1]"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify([changes, navigates])").unwrap(),
+ "[1,2]"
+ );
+ vm.eval("history.pushState({}, '', '#page'); 'pushed'")
+ .unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(isolated, "String(changes)")
+ .unwrap(),
+ "2"
+ );
+}
+
+#[test]
+fn history_worlds_security_errors_belong_to_the_binding_realm() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ let isolated = vm.create_isolated_world("errors", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"JSON.stringify(
+ ['pushState', 'replaceState'].flatMap(method => {
+ try { history[method]({}, '', 'https://other.test/'); }
+ catch (error) { return [error.name, error instanceof DOMException,
+ Object.getPrototypeOf(error) === DOMException.prototype]; }
+ return ['did not throw'];
+ })
+ )"#
+ )
+ .unwrap(),
+ r#"["SecurityError",true,true,"SecurityError",true,true]"#
+ );
+}
+
+#[test]
+fn history_worlds_navigation_events_use_local_views_and_one_dispatch_state() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.pageEvents = [];
+ globalThis.pageEntry = navigation.currentEntry;
+ navigation.addEventListener('navigate', function (event) {
+ pageEvents.push([this === navigation, event.target === navigation,
+ event instanceof NavigateEvent, event.defaultPrevented]);
+ event.expando = 'page';
+ event.preventDefault = () => { throw new Error('page override'); };
+ event.destination.getState = () => 'page override';
+ });
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("event-views", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ globalThis.initialEntry = navigation.currentEntry;
+ globalThis.savedEvent = null;
+ globalThis.seen = [];
+ navigation.addEventListener('navigate', function (event) {
+ savedEvent = event;
+ try {
+ seen.push([this === navigation, event.target === navigation,
+ event.currentTarget === navigation, event instanceof NavigateEvent,
+ event.composedPath()[0] === navigation, event.expando === undefined,
+ Object.getPrototypeOf(event.destination.getState) === Function.prototype,
+ Object.getPrototypeOf(event.destination.getState()) === Object.prototype]);
+ } catch (error) { seen.push(String(error)); }
+ event.preventDefault();
+ }, {once: true});
+ history.pushState({value: 1}, '', '#cancelled');
+ JSON.stringify([seen, savedEvent.defaultPrevented, savedEvent.currentTarget,
+ savedEvent.eventPhase, savedEvent.composedPath().length,
+ location.hash, navigation.currentEntry === initialEntry])
+ "##
+ )
+ .unwrap(),
+ r#"[[[true,true,true,true,true,true,true,true]],true,null,0,0,"",true]"#
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify(pageEvents)").unwrap(),
+ "[[true,true,true,false]]"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ globalThis.from = null;
+ navigation.oncurrententrychange = function (event) {
+ from = event.from;
+ seen.push([this === navigation, event.currentTarget === navigation,
+ event instanceof NavigationCurrentEntryChangeEvent,
+ event.from instanceof NavigationHistoryEntry,
+ event.from === initialEntry]);
+ };
+ history.pushState({}, '', '#committed');
+ JSON.stringify(seen[1])
+ "##
+ )
+ .unwrap(),
+ "[true,true,true,true,true]"
+ );
+}
+
+#[test]
+fn history_worlds_navigation_handlers_and_dispose_listeners_share_target_identity() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.pageCalls = 0;
+ globalThis.pageDisposed = 0;
+ navigation.oncurrententrychange = () => pageCalls++;
+ navigation.currentEntry.ondispose = () => pageDisposed++;
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("handlers", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ const entry = navigation.currentEntry;
+ let disposed = 0;
+ let calls = 0;
+ let handler = () => calls++;
+ navigation.oncurrententrychange = handler;
+ entry.addEventListener('dispose', function (event) {
+ if (this === entry && event.target === entry && event instanceof Event) disposed++;
+ }, {once: true});
+ entry.ondispose = () => disposed++;
+ history.replaceState({}, '', '#replaced');
+ navigation.oncurrententrychange = null;
+ history.pushState({}, '', '#pushed');
+ JSON.stringify([calls, disposed, navigation.oncurrententrychange, entry.index])
+ "##
+ )
+ .unwrap(),
+ "[1,2,null,-1]"
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify([pageCalls, pageDisposed])")
+ .unwrap(),
+ "[2,1]"
+ );
+}
+
+#[test]
+fn history_worlds_navigation_results_and_transition_use_the_callers_wrappers() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ let isolated = vm.create_isolated_world("results", false).unwrap();
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r##"
+ globalThis.facts = [];
+ const from = navigation.currentEntry;
+ navigation.addEventListener('navigate', event => {
+ event.intercept({handler() {
+ const transition = navigation.transition;
+ facts.push([transition instanceof NavigationTransition,
+ transition.from === from, transition.to === event.destination,
+ transition.committed instanceof Promise,
+ transition.finished instanceof Promise, this === event]);
+ }});
+ }, {once: true});
+ const result = navigation.navigate('#next');
+ result.committed.then(entry => facts.push(['committed',
+ entry instanceof NavigationHistoryEntry, entry === navigation.currentEntry]));
+ result.finished.then(entry => facts.push(['finished',
+ entry instanceof NavigationHistoryEntry, entry === navigation.currentEntry]));
+ String(result.committed instanceof Promise && result.finished instanceof Promise)
+ "##
+ )
+ .unwrap(),
+ "true"
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(isolated, "JSON.stringify(facts)")
+ .unwrap(),
+ r#"[[true,true,true,true,true,true],["committed",true,true],["finished",true,true]]"#
+ );
+}
+
+#[test]
+fn history_worlds_navigation_listener_order_cancellation_and_event_reuse_are_shared() {
+ let mut vm = new_storage_test_vm("https://example.com/base");
+ vm.eval(
+ r#"
+ globalThis.order = [];
+ navigation.addEventListener('navigate', event => {
+ order.push('first:' + event.defaultPrevented);
+ });
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ let isolated = vm.create_isolated_world("ordered-dispatch", false).unwrap();
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ globalThis.saved = null;
+ navigation.addEventListener('navigate', event => {
+ saved = event;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }, {once: true});
+ 'ready'
+ "#,
+ )
+ .unwrap();
+ vm.eval(r#"
+ navigation.addEventListener('navigate', event => order.push('last:' + event.defaultPrevented));
+ history.pushState({}, '', '#blocked');
+ 'pushed'
+ "#).unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify([order, location.hash])").unwrap(),
+ r#"[["first:false"],""]"#
+ );
+ assert_eq!(
+ vm.eval_in_isolated_context(
+ isolated,
+ r#"
+ const trusted = saved.isTrusted;
+ saved.initEvent('probe', false, true);
+ let calls = 0;
+ navigation.addEventListener('probe', event => {
+ if (event === saved && event.target === navigation && !event.isTrusted) calls++;
+ event.preventDefault();
+ });
+ const result = navigation.dispatchEvent(saved);
+ JSON.stringify([trusted, calls, result, saved.defaultPrevented,
+ saved.currentTarget, saved.eventPhase, saved.composedPath().length])
+ "#
+ )
+ .unwrap(),
+ "[true,1,false,true,null,0,0]"
+ );
+ vm.eval("history.pushState({}, '', '#allowed'); 'pushed'")
+ .unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify([order, location.hash])").unwrap(),
+ r##"[["first:false","first:false","last:false"],"#allowed"]"##
+ );
+}
+
#[tokio::test]
async fn history_worlds_share_mutations_but_keep_wrappers_and_state_caches_separate() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
index 73e27e2f6..639b49269 100644
--- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
+++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
@@ -99,7 +99,9 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[
),
allowed(
"context_bootstrap/navigation_lifecycle.rs",
- 6,
+ // Committed and deferred fulfillment share one realm-aware settlement
+ // helper. The other two calls reject browser-owned Promise capabilities.
+ 3,
DirectCallOwner::BrowserAlgorithm,
),
allowed(