fix(popup): keep DOM event propagation in the owning Window

This commit is contained in:
ldm0
2026-11-22 02:01:53 +08:00
parent 98de5f13f3
commit f4d11c05e2
13 changed files with 398 additions and 20 deletions
+20 -10
View File
@@ -39,7 +39,7 @@ impl DocumentRuntime {
let dom_host = &self.dom_host;
self.events.clear_targets_matching(|target| match target {
EventTargetHandle::Window => clear_window,
EventTargetHandle::ChildWindow(_) => clear_window,
EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_) => clear_window,
EventTargetHandle::Node(handle) => {
// Retiring a browsing context can disconnect the native tree
// without removing its Document/child relationships.
@@ -518,7 +518,7 @@ impl DocumentRuntime {
} else {
self.build_propagation_path(dispatch_target, composed)
};
self.append_child_document_window_to_path(scope, host_ptr, &mut path);
self.append_document_window_to_path(scope, host_ptr, &mut path);
trim_window_from_subresource_load_path(dispatch_target, event_type.as_deref(), &mut path);
dispatch_public_event(
&mut self.events,
@@ -588,16 +588,18 @@ impl DocumentRuntime {
path
}
fn append_child_document_window_to_path(
fn append_document_window_to_path(
&self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
path: &mut Vec<EventTargetHandle>,
) {
if path
.iter()
.any(|target| matches!(target, EventTargetHandle::ChildWindow(_)))
{
if path.iter().any(|target| {
matches!(
target,
EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_)
)
}) {
return;
}
let trailing_main_window = path.last() == Some(&EventTargetHandle::Window);
@@ -625,6 +627,14 @@ impl DocumentRuntime {
path.pop();
}
path.push(EventTargetHandle::ChildWindow(target));
} else if let Some(popup_id) =
host.lightweight_popup_id_for_document_handle(document_handle)
&& let Some(target) = host.current_popup_window_event_target(popup_id)
{
if trailing_main_window {
path.pop();
}
path.push(EventTargetHandle::PopupWindow(target));
}
}
@@ -647,9 +657,9 @@ impl DocumentRuntime {
let mut filtered = Vec::new();
for entry in full_path {
let include = match entry {
EventTargetHandle::Window | EventTargetHandle::ChildWindow(_) => {
source_root_is_document
}
EventTargetHandle::Window
| EventTargetHandle::ChildWindow(_)
| EventTargetHandle::PopupWindow(_) => source_root_is_document,
EventTargetHandle::Node(handle) => {
self.dom_host.root_node_handle(handle) == Some(source_root)
|| self.flat_tree_contains_for_event_path(handle, target_handle)
+11 -1
View File
@@ -43,16 +43,26 @@ impl ChildWindowEventTarget {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct PopupWindowEventTarget {
pub(crate) document_owner: crate::window_document_identity::LightweightPopupDocumentOwner,
pub(crate) local_window_id: crate::window_document_identity::LightweightPopupLocalWindowId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum EventTargetHandle {
Window,
ChildWindow(ChildWindowEventTarget),
PopupWindow(PopupWindowEventTarget),
Node(NativeNodeId),
}
impl EventTargetHandle {
pub(crate) fn is_window(self) -> bool {
matches!(self, Self::Window | Self::ChildWindow(_))
matches!(
self,
Self::Window | Self::ChildWindow(_) | Self::PopupWindow(_)
)
}
}
+28 -1
View File
@@ -624,6 +624,18 @@ fn call_event_target_listeners_filtered<'s>(
),
);
}
if let EventTargetHandle::PopupWindow(target) = target {
return Ok(
unsafe { &mut *host_ptr }.call_popup_window_event_path_listeners(
scope,
target,
event_type,
event,
capture_only,
at_target,
),
);
}
registry.call_listeners_filtered(
scope,
host_ptr,
@@ -645,6 +657,9 @@ fn event_target_is_current(host_ptr: *mut PageScriptHost, target: EventTargetHan
EventTargetHandle::ChildWindow(target) => {
unsafe { &*host_ptr }.child_window_event_target_is_current(target)
}
EventTargetHandle::PopupWindow(target) => {
unsafe { &*host_ptr }.popup_window_event_target_is_current(target)
}
EventTargetHandle::Window | EventTargetHandle::Node(_) => true,
}
}
@@ -2186,6 +2201,9 @@ fn event_target_object<'s>(
EventTargetHandle::ChildWindow(target) => unsafe { &mut *host_ptr }
.child_window_event_target_wrapper(scope, target)
.ok_or_else(|| format!("stale child Window event target `{target:?}`")),
EventTargetHandle::PopupWindow(target) => unsafe { &*host_ptr }
.popup_window_event_target_wrapper(scope, target)
.ok_or_else(|| format!("stale popup Window event target `{target:?}`")),
EventTargetHandle::Node(handle) => {
let wrapper = unsafe { &mut *host_ptr }
.native_bridge_mut()
@@ -2206,6 +2224,9 @@ pub(crate) fn event_target_value<'s>(
EventTargetHandle::ChildWindow(target) => {
event_target_object(scope, host_ptr, EventTargetHandle::ChildWindow(target))?.into()
}
EventTargetHandle::PopupWindow(target) => {
event_target_object(scope, host_ptr, EventTargetHandle::PopupWindow(target))?.into()
}
EventTargetHandle::Node(handle) => {
event_target_object(scope, host_ptr, EventTargetHandle::Node(handle))?.into()
}
@@ -2224,6 +2245,10 @@ fn event_target_receiver<'s>(
.child_window_event_target_wrapper(scope, target)
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into()),
EventTargetHandle::PopupWindow(target) => unsafe { &*host_ptr }
.popup_window_event_target_wrapper(scope, target)
.map(Into::into)
.unwrap_or_else(|| v8::undefined(scope).into()),
EventTargetHandle::Node(_) => {
let key = v8str(scope, "currentTarget");
crate::context_bootstrap::event_backing(scope, event)
@@ -2585,7 +2610,9 @@ fn current_target_can_access_shadow_root(
) -> bool {
let runtime = unsafe { &*host_ptr };
match current_target {
EventTargetHandle::Window | EventTargetHandle::ChildWindow(_) => false,
EventTargetHandle::Window
| EventTargetHandle::ChildWindow(_)
| EventTargetHandle::PopupWindow(_) => false,
EventTargetHandle::Node(handle) => {
shadow_including_tree_contains(runtime.dom_host(), shadow_root, handle)
}
@@ -322,7 +322,9 @@ impl PageScriptHost {
return None;
}
let target_name = match target {
EventTargetHandle::Window | EventTargetHandle::ChildWindow(_) => "Window".to_owned(),
EventTargetHandle::Window
| EventTargetHandle::ChildWindow(_)
| EventTargetHandle::PopupWindow(_) => "Window".to_owned(),
EventTargetHandle::Node(handle) => self
.dom_host()
.node(handle)
@@ -146,6 +146,7 @@ impl PageScriptHost {
)
}
crate::document_runtime::EventTargetHandle::Window
| crate::document_runtime::EventTargetHandle::PopupWindow(_)
| crate::document_runtime::EventTargetHandle::Node(_) => {
self.event_listener_callback_ids(target, event_type, capture)
}
@@ -171,6 +172,7 @@ impl PageScriptHost {
);
}
crate::document_runtime::EventTargetHandle::Window
| crate::document_runtime::EventTargetHandle::PopupWindow(_)
| crate::document_runtime::EventTargetHandle::Node(_) => {
let registration = crate::host::EventListenerRegistration::new(
scope,
@@ -202,6 +204,7 @@ impl PageScriptHost {
capture,
),
crate::document_runtime::EventTargetHandle::Window
| crate::document_runtime::EventTargetHandle::PopupWindow(_)
| crate::document_runtime::EventTargetHandle::Node(_) => {
self.event_listener_callback_ids(target, event_type, capture)
}
@@ -221,6 +224,7 @@ impl PageScriptHost {
capture,
),
crate::document_runtime::EventTargetHandle::Window
| crate::document_runtime::EventTargetHandle::PopupWindow(_)
| crate::document_runtime::EventTargetHandle::Node(_) => {
self.remove_event_listener_by_id(target, event_type, callback_id, capture)
}
@@ -22,7 +22,7 @@ use crate::{
},
document_runtime::create_content_security_policy_violation_event,
document_runtime::{DocumentPolicyContainer, DocumentSandboxPolicy, DomHandle},
host::HostTimerOwner,
host::{DispatchStatus, HostTimerOwner, PopupWindowEventTarget, event_dispatch_status},
native_bridge::{
OwnerDispatchScope, WindowTaskTarget,
document::set_document_associated_window,
@@ -3197,6 +3197,105 @@ impl PageScriptHost {
.retire_document_style_world(document_handle);
}
pub(crate) fn current_popup_window_event_target(
&self,
popup_id: u64,
) -> Option<PopupWindowEventTarget> {
let document = self.lightweight_popup_document_record(popup_id)?;
Some(PopupWindowEventTarget {
document_owner: document.owner,
local_window_id: document.local_window_id,
})
}
pub(crate) fn popup_window_event_target_is_current(
&self,
target: PopupWindowEventTarget,
) -> bool {
self.current_popup_window_event_target(target.document_owner.popup_id()) == Some(target)
}
pub(crate) fn popup_window_event_target_wrapper<'s>(
&self,
scope: &mut v8::PinScope<'s, '_>,
target: PopupWindowEventTarget,
) -> Option<v8::Local<'s, v8::Object>> {
self.popup_window_event_target_is_current(target)
.then(|| self.lightweight_popup_window(scope, target.document_owner.popup_id()))
.flatten()
}
pub(crate) fn call_popup_window_event_path_listeners<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
target: PopupWindowEventTarget,
event_type: &str,
event: v8::Local<'s, v8::Object>,
capture_only: bool,
at_target: bool,
) -> DispatchStatus {
let Some(window) = self.popup_window_event_target_wrapper(scope, target) else {
return DispatchStatus::StopPropagation;
};
if at_target && !capture_only {
return DispatchStatus::Continue;
}
let Some(context) = window.get_creation_context(scope) else {
return DispatchStatus::StopPropagation;
};
let scope = &mut v8::ContextScope::new(scope, context);
let popup_id = target.document_owner.popup_id();
if !self.register_lightweight_popup_execution_context(scope, popup_id) {
return DispatchStatus::StopPropagation;
}
let previous = enter_lightweight_popup_event_dispatch(scope, popup_id);
let previous_message_source = self.enter_window_message_source_scope(
super::PendingWindowMessageEndpoint::LightweightPopup(popup_id),
);
let error_arguments = (event_type == "error")
.then(|| crate::context_bootstrap::error_event_handler_arguments(scope, event))
.flatten();
let ordinary_arguments = [event.into()];
let handler_arguments = error_arguments
.as_ref()
.map_or(ordinary_arguments.as_slice(), |values| values.as_slice());
let handler_type = if error_arguments.is_some() {
crate::context_bootstrap::EventHandlerType::OnErrorEventHandler
} else {
crate::context_bootstrap::EventHandlerType::EventHandler
};
// The DOM dispatcher owns target, phase, path and cleanup. Invoke only
// this Window's listener phase without starting a second dispatch.
for capture in [true, false] {
if !at_target && capture != capture_only {
continue;
}
crate::context_bootstrap::invoke_simple_event_target_listeners(
scope,
window,
LIGHTWEIGHT_POPUP_EVENT_LISTENERS_SLOT,
event_type,
event,
capture,
handler_arguments,
handler_type,
None,
);
if event_dispatch_status(scope, event) != DispatchStatus::Continue
|| !self.popup_window_event_target_is_current(target)
{
break;
}
}
self.restore_window_message_source_scope(previous_message_source);
restore_lightweight_popup_event_dispatch(scope, previous);
if self.popup_window_event_target_is_current(target) {
event_dispatch_status(scope, event)
} else {
DispatchStatus::StopPropagation
}
}
pub(crate) fn dispatch_lightweight_popup_window_event<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
@@ -104,7 +104,7 @@ impl PageScriptHost {
EventTargetHandle::Node(handle) => {
self.window_document_task_target_for_node(scope, handle)
}
EventTargetHandle::ChildWindow(_) => None,
EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_) => None,
};
let Some(target) = target else {
return false;
@@ -86,6 +86,7 @@ impl PageScriptHost {
capture,
),
crate::document_runtime::EventTargetHandle::Window
| crate::document_runtime::EventTargetHandle::PopupWindow(_)
| crate::document_runtime::EventTargetHandle::Node(_) => {
self.remove_event_listener_by_id(target, event_type, callback_id, capture)
}
@@ -918,6 +918,7 @@ pub(crate) fn dispatched_click_activation_target(
}
EventTargetHandle::Window
| EventTargetHandle::ChildWindow(_)
| EventTargetHandle::PopupWindow(_)
| EventTargetHandle::Node(_) => None,
})
}
@@ -69,7 +69,7 @@ pub(crate) fn dispatch_animation_start_scan(
EventTargetHandle::Node(handle) => {
dispatch_animation_start_if_applies(scope, runtime_ptr, handle)
}
EventTargetHandle::ChildWindow(_) => false,
EventTargetHandle::ChildWindow(_) | EventTargetHandle::PopupWindow(_) => false,
}
}
@@ -258,9 +258,9 @@ fn host_listener_snapshots(
EventTargetHandle::ChildWindow(target) => {
host.child_window_inspector_listener_snapshots(target)
}
EventTargetHandle::Window | EventTargetHandle::Node(_) => {
host.inspector_event_listener_snapshots(target)
}
EventTargetHandle::Window
| EventTargetHandle::PopupWindow(_)
| EventTargetHandle::Node(_) => host.inspector_event_listener_snapshots(target),
}
}
@@ -1,5 +1,227 @@
use super::*;
#[test]
fn popup_dom_events_propagate_through_their_window_without_reaching_the_opener() {
let mut vm = new_storage_test_vm("https://popup-event-path.test/");
let result = vm
.eval(
r#"
(() => {
const popup = open();
try {
const doc = popup.document;
const button = doc.body.appendChild(doc.createElement('button'));
const trace = [];
const label = node => node === popup ? 'popup' : node === doc ? 'document' :
node === button ? 'button' : node === doc.body ? 'body' :
node === doc.documentElement ? 'html' : 'foreign';
let expectedTarget;
const record = name => function(event) {
trace.push([name, event.eventPhase, event.target === expectedTarget,
this === event.currentTarget, event.composedPath().map(label)]);
};
window.addEventListener('popup-probe', record('opener-capture'), true);
window.addEventListener('popup-probe', record('opener-bubble'));
popup.addEventListener('popup-probe', record('window-capture'), true);
popup.addEventListener('popup-probe', record('window-bubble'));
doc.addEventListener('popup-probe', record('document-capture'), true);
doc.addEventListener('popup-probe', record('document-bubble'));
button.addEventListener('popup-probe', record('button'));
const results = [];
for (const target of [doc, button]) {
for (const bubbles of [false, true]) {
trace.length = 0;
expectedTarget = target;
const event = new Event('popup-probe', {bubbles});
target.dispatchEvent(event);
results.push({trace:trace.slice(), clean:event.currentTarget === null &&
event.eventPhase === 0 && event.composedPath().length === 0 && event.target === target});
}
}
return JSON.stringify(results);
} finally { popup.close(); }
})()
"#,
)
.expect("popup event path probe should run");
let doc_path = serde_json::json!(["document", "popup"]);
let button_path = serde_json::json!(["button", "body", "html", "document", "popup"]);
let row = |name: &str, phase: u8, path: &serde_json::Value| {
serde_json::json!([name, phase, true, true, path])
};
let doc_capture = vec![
row("window-capture", 1, &doc_path),
row("document-capture", 2, &doc_path),
row("document-bubble", 2, &doc_path),
];
let mut doc_bubble = doc_capture.clone();
doc_bubble.push(row("window-bubble", 3, &doc_path));
let button_capture = vec![
row("window-capture", 1, &button_path),
row("document-capture", 1, &button_path),
row("button", 2, &button_path),
];
let mut button_bubble = button_capture.clone();
button_bubble.extend([
row("document-bubble", 3, &button_path),
row("window-bubble", 3, &button_path),
]);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!([
{"trace":doc_capture, "clean":true},
{"trace":doc_bubble, "clean":true},
{"trace":button_capture, "clean":true},
{"trace":button_bubble, "clean":true},
])
);
}
#[test]
fn popup_dom_event_paths_keep_child_frames_and_load_events_isolated() {
let mut vm = new_storage_test_vm("https://popup-event-boundaries.test/");
let result = vm
.eval(
r#"
(() => {
const popup = open();
const sibling = open();
try {
const doc = popup.document;
const frame = doc.body.appendChild(doc.createElement('iframe'));
const child = frame.contentWindow;
const trace = [];
for (const [name, target] of [['opener',window], ['sibling',sibling], ['popup',popup]]) {
target.addEventListener('child-probe', () => trace.push(name), true);
target.addEventListener('load', () => trace.push(name + '-load'), true);
}
child.addEventListener('child-probe', event => {
trace.push(['child-capture',event.eventPhase,event.target === child.document,
event.composedPath().length === 2,event.composedPath().at(-1) === child]);
}, true);
child.addEventListener('child-probe', event => trace.push(['child-bubble',event.eventPhase]));
child.document.dispatchEvent(new Event('child-probe', {bubbles:true}));
doc.addEventListener('load', event => trace.push(['document-load',event.eventPhase,
event.composedPath().at(-1) === doc]));
doc.dispatchEvent(new Event('load', {bubbles:true}));
const image = doc.body.appendChild(doc.createElement('img'));
image.dispatchEvent(new Event('load', {bubbles:true}));
return JSON.stringify(trace);
} finally { popup.close(); sibling.close(); }
})()
"#,
)
.expect("popup document event boundaries should be preserved");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!([
["child-capture", 1, true, true, true],
["child-bubble", 3],
["document-load", 2, true],
["document-load", 3, true],
])
);
}
#[test]
fn popup_dom_event_path_preserves_listener_mutation_cancellation_and_stop_rules() {
let mut vm = new_storage_test_vm("https://popup-event-listeners.test/");
let result = vm
.eval(
r#"
(() => {
const popup = open();
try {
const button = popup.document.body.appendChild(popup.document.createElement('button'));
const trace = [];
const removed = () => trace.push('removed');
const added = () => trace.push('added');
popup.addEventListener('click', () => {
trace.push('capture');
popup.removeEventListener('click', removed, true);
popup.addEventListener('click', added);
}, {capture:true, once:true});
popup.addEventListener('click', removed, true);
popup.addEventListener('click', event => {
event.preventDefault();
trace.push('passive:' + event.defaultPrevented);
}, {passive:true});
popup.onclick = function(event) {
trace.push('handler:' + (this === popup && event.currentTarget === popup));
return false;
};
button.addEventListener('click', () => trace.push('target'));
const canceled = [];
for (let n = 0; n < 2; ++n) {
canceled.push(!button.dispatchEvent(new Event('click', {bubbles:true, cancelable:true})));
}
const stopped = [];
for (const immediate of [false, true]) {
const type = 'stop-' + immediate;
popup.addEventListener(type, event => {
stopped.push('first:' + immediate);
if (immediate) event.stopImmediatePropagation(); else event.stopPropagation();
}, true);
popup.addEventListener(type, () => stopped.push('second:' + immediate), true);
button.addEventListener(type, () => stopped.push('target'));
button.dispatchEvent(new Event(type, {bubbles:true}));
}
return JSON.stringify({trace,canceled,stopped});
} finally { popup.close(); }
})()
"#,
)
.expect("popup listener semantics probe should run");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!({
"trace":["capture", "target", "passive:false", "handler:true", "added",
"target", "passive:false", "handler:true", "added"],
"canceled":[true,true],
"stopped":["first:false", "second:false", "first:true"],
})
);
}
#[test]
fn popup_dom_event_paths_retarget_closed_shadows_and_retire_replaced_documents() {
let mut vm = new_storage_test_vm("https://popup-event-retarget.test/");
let result = vm.eval(r#"
(() => {
const popup = open('about:blank', 'popup-event-retarget');
try {
const doc = popup.document;
const host = doc.body.appendChild(doc.createElement('div'));
const shadow = host.attachShadow({mode:'closed'});
const button = shadow.appendChild(doc.createElement('button'));
const trace = [];
popup.addEventListener('shadow-probe', event => {
const path = event.composedPath();
trace.push(['shadow', event.target === host, event.currentTarget === popup,
path[0] === host, path.at(-1) === popup, !path.includes(button), !path.includes(shadow)]);
});
button.dispatchEvent(new Event('shadow-probe', {bubbles:true, composed:true}));
let openerCalls = 0;
window.addEventListener('retained-probe', () => ++openerCalls);
popup.addEventListener('retained-probe', () => trace.push('retired-window'));
open('about:blank', 'popup-event-retarget');
const replaced = doc !== popup.document;
popup.addEventListener('retained-probe', event => trace.push(['current', event.target === popup.document]));
doc.dispatchEvent(new Event('retained-probe', {bubbles:true}));
popup.document.dispatchEvent(new Event('retained-probe', {bubbles:true}));
return JSON.stringify({trace,replaced,openerCalls});
} finally { popup.close(); }
})()
"#).expect("popup retargeting and replacement probe should run");
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!({
"trace":[["shadow",true,true,true,true,true,true],["current",true]],
"replaced":true,"openerCalls":0,
})
);
}
#[test]
fn popup_content_handlers_use_their_window_document_form_and_element_scopes() {
let mut vm = new_storage_test_vm("https://popup-content-handler.test/");
+3 -1
View File
@@ -318,7 +318,9 @@ fn default_passive_value(
return false;
}
match target {
EventTargetHandle::Window | EventTargetHandle::ChildWindow(_) => true,
EventTargetHandle::Window
| EventTargetHandle::ChildWindow(_)
| EventTargetHandle::PopupWindow(_) => true,
EventTargetHandle::Node(handle) => {
let dom_host = host.dom_host();
if dom_host