fix(focus): check the native document ancestor chain

Compute Document.hasFocus from the branded receiver, current document owners, page activity, and every ancestor’s focused area. Retained child focus must not report true when an outer ancestor selected another target.

Avoid observable property reads from defaultView, frameElement, and activeElement while computing native focus. Cover nested focus, document retirement, page deactivation, receiver branding, and author property overrides.
This commit is contained in:
ldm0
2026-11-08 11:29:37 +08:00
parent 5d6137f2bc
commit bd92a1c093
3 changed files with 95 additions and 27 deletions
@@ -127,33 +127,22 @@ pub(super) fn document_has_focus_callback(
args: v8::FunctionCallbackArguments<'_>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let document = args.this();
let focused = document
.get(scope, v8str(scope, "defaultView").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
.map(|default_view| {
default_view
.get(scope, v8str(scope, "frameElement").into())
.filter(|value| !value.is_null_or_undefined())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
.map(|frame_element| {
frame_element
.get(scope, v8str(scope, "ownerDocument").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
.and_then(|owner_document| {
owner_document.get(scope, v8str(scope, "activeElement").into())
})
.is_some_and(|active_element| {
active_element.strict_equals(frame_element.into())
})
})
.unwrap_or(true)
})
.unwrap_or(false);
let focused = focused
&& context_host_ptr_from_global_bridge(scope)
.is_some_and(|host_ptr| unsafe { &*host_ptr }.document_activity().focused);
rv.set_bool(focused);
let Ok((host_ptr, document)) =
crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, args.this())
else {
webidl::throw_type_error(scope, "Document.hasFocus called on incompatible receiver.");
return;
};
let host = unsafe { &*host_ptr };
if !host
.dom_host()
.node(document)
.is_some_and(crate::dom::native::Node::is_document)
{
webidl::throw_type_error(scope, "Document.hasFocus called on incompatible receiver.");
return;
}
rv.set_bool(host.document_has_focus(document));
}
#[cfg(test)]
@@ -13,6 +13,31 @@ pub(super) struct DocumentFocusChangeState {
}
impl JsContextHost {
pub(crate) fn document_has_focus(&self, document: DomHandle) -> bool {
if !self.document_activity().focused || !self.document_is_fully_active(document) {
return false;
}
let mut document = document;
loop {
match self.window_endpoint_for_document(document) {
Some(PendingWindowMessageEndpoint::TopWindow)
| Some(PendingWindowMessageEndpoint::LightweightPopup(_)) => return true,
Some(PendingWindowMessageEndpoint::ChildWindow(container)) => {
let Some(parent) = self.dom_host().owner_document_handle(container) else {
return false;
};
// Inactive Documents retain their local focused area. Every
// ancestor must still select this child's navigable.
if self.document_focused_area(parent) != Some(container) {
return false;
}
document = parent;
}
None => return false,
}
}
}
pub(crate) fn focused_viewport_document(&self) -> Option<DomHandle> {
self.focused_viewport_document.filter(|document| {
self.active_element_handle().is_none()
@@ -1,5 +1,59 @@
use super::*;
#[test]
fn document_has_focus_checks_every_live_ancestor_in_the_native_focus_chain() {
let mut vm = new_storage_test_vm("https://document-focus-chain.test/");
let result = vm.eval(r#"(() => {
const root = document.documentElement || document.appendChild(document.createElement('html'));
const body = document.body || root.appendChild(document.createElement('body'));
body.innerHTML = '<input id=top><iframe id=outer></iframe>';
const outer = document.getElementById('outer');
const middle = outer.contentDocument;
middle.body.innerHTML = '<input id=middle><iframe id=inner></iframe>';
const inner = middle.getElementById('inner');
const deep = inner.contentDocument;
deep.body.innerHTML = '<input id=deep>';
const state = () => [document.hasFocus(), middle.hasFocus(), deep.hasFocus()].join(',');
const states = [state()];
deep.getElementById('deep').focus();
states.push(state());
document.getElementById('top').focus();
states.push(state());
if (middle.activeElement !== inner) throw Error('inactive child lost its local focused area');
middle.getElementById('middle').focus();
states.push(state());
deep.getElementById('deep').focus();
states.push(state());
outer.remove();
states.push(state());
if (document.implementation.createHTMLDocument('').hasFocus()) throw Error('detached Document focused');
window.checkFocusState = state;
return states.join('|');
})()"#).unwrap();
assert_eq!(
result,
"true,false,false|true,true,true|true,false,false|true,true,false|true,true,true|true,false,false"
);
vm.set_document_activity(moli_page_types::DocumentActivity::new(false, true))
.unwrap();
assert_eq!(vm.eval("checkFocusState()").unwrap(), "false,false,false");
}
#[test]
fn document_has_focus_uses_the_branded_receiver_without_reading_author_properties() {
let mut vm = new_storage_test_vm("https://document-focus-receiver.test/");
assert_eq!(vm.eval(r#"(() => {
const hasFocus = Document.prototype.hasFocus;
for (const receiver of [{defaultView: window}, Object.create(document), new Proxy(document, {}), document.createElement('div')]) {
let error;
try { hasFocus.call(receiver); } catch (caught) { error = caught; }
if (!(error instanceof TypeError)) throw Error('invalid Document receiver accepted');
}
Object.defineProperty(document, 'defaultView', {get() { throw Error('author defaultView getter invoked'); }});
return hasFocus.call(document);
})()"#).unwrap(), "true");
}
#[test]
fn window_focus_and_blur_validate_the_receiver_in_the_callee_realm() {
let mut vm = new_storage_test_vm("https://window-focus-native.test/");