Truly independent web browser
LibWeb: Skip event listeners of documents that aren’t fully active
sideshowbarker5833cbb29c1c
diff --git a/Libraries/LibWeb/DOM/BindingsGlue.h b/Libraries/LibWeb/DOM/BindingsGlue.hindex 838d8613d09..4ae22f8c7f6 100644--- a/Libraries/LibWeb/DOM/BindingsGlue.h+++ b/Libraries/LibWeb/DOM/BindingsGlue.h@@ -52,6 +52,7 @@ WEB_API void remove_event_listener(DOM::EventTarget&, Utf16String const&, GC::PtWEB_API GC::Ref<JS::Environment> new_event_handler_object_environment(JS::Realm&, GC::Ref<DOM::EventTarget>, GC::Ref<JS::Environment>);WEB_API JS::Realm* callback_realm(WebIDL::CallbackType*);WEB_API HTML::Window* window_from_callback(WebIDL::CallbackType&);+WEB_API DOM::EventTarget* current_target_global(WebIDL::CallbackType&, DOM::Event const&);WEB_API void report_exception_for_callback(WebIDL::CallbackType&, JS::Value);WEB_API JS::Completion invoke_event_listener(WebIDL::CallbackType&, DOM::Event&);WEB_API JS::Completion invoke_event_handler(WebIDL::CallbackType&, DOM::Event&, bool);diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 17979baf4f2..b03abc42a3b 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -4938,10 +4938,12 @@ bool Document::compute_is_fully_active() const// NB: A destroyed navigable has no container, but its document keeps its navigable until it has unloaded, which// happens after a round-trip through the UI process.- // INTEROP: Other engines unload the document of a removed iframe before they detach it, so its pagehide and unload- // handlers see a fully active document.- if (navigable->is_in_a_destroyed_subtree() && m_unload_counter == 0)- return false;+ // INTEROP: Other engines unload the documents of a removed iframe — its own and its descendants' — before they+ // detach it, so their pagehide, visibilitychange, and unload handlers see fully active documents. So a+ // document in a destroyed subtree is fully active exactly while it's unloading, whether or not the document+ // its container belongs to has started unloading yet.+ if (navigable->is_in_a_destroyed_subtree())+ return m_unload_counter > 0;if (navigable->is_top_level_traversable())return true;diff --git a/Libraries/LibWeb/DOM/EventDispatcher.cpp b/Libraries/LibWeb/DOM/EventDispatcher.cppindex 9531037cdb0..1e46ac010f8 100644--- a/Libraries/LibWeb/DOM/EventDispatcher.cpp+++ b/Libraries/LibWeb/DOM/EventDispatcher.cpp@@ -51,6 +51,10 @@ bool EventDispatcher::inner_invoke(Event& event, EventTarget::ClonedEventListene// 1. Let found be false.bool found = false;+ // NB: Event's currentTarget stays the same while its listeners run, so it's only checked once for being a node —+ // and not at all when it has no listeners for the event, as most targets in an event's path don't.+ auto* current_target_node = listeners.is_empty() ? nullptr : as_if<Node>(event.current_target().ptr());+// 2. For each listener of listeners, whose removed is false:for (auto& listener : listeners) {if (listener->removed)@@ -75,30 +79,47 @@ bool EventDispatcher::inner_invoke(Event& event, EventTarget::ClonedEventListeneif (listener->once)event.current_target()->remove_an_event_listener(*listener);- // 6. Let global be listener callback’s associated Realm’s global object.auto& callback = listener->callback->callback();- // 7. Let currentEvent be undefined.+ // 6. Let targetGlobal be event's currentTarget's node document's relevant global object if event's currentTarget+ // is a node; otherwise event's currentTarget's relevant global object.+ auto* target_global = current_target_node+ ? current_target_node->document().relevant_global_event_target().ptr()+ : Bindings::current_target_global(callback, event);++ // 7. Let listenerGlobal be listener callback's associated realm's global object.+ auto* listener_window = Bindings::window_from_callback(callback);++ // 8. If targetGlobal or listenerGlobal is a Window object whose associated Document is not fully active, then+ // continue.+ if (listener_window && !listener_window->associated_document().is_fully_active())+ continue;+ // NB: Mostly, targetGlobal is listenerGlobal, which was just checked.+ if (target_global != listener_window) {+ if (auto* target_window = as_if<HTML::Window>(target_global); target_window && !target_window->associated_document().is_fully_active())+ continue;+ }++ // 9. Let currentEvent be undefined.Event* current_event = nullptr;- // 8. If global is a Window object, then:- auto* window = Bindings::window_from_callback(callback);- if (window) {- // 1. Set currentEvent to global’s current event.- current_event = window->current_event();+ // 10. If listenerGlobal is a Window object:+ if (listener_window) {+ // 1. Set currentEvent to listenerGlobal's current event.+ current_event = listener_window->current_event();- // 2. If invocationTargetInShadowTree is false, then set global’s current event to event.+ // 2. If invocationTargetInShadowTree is false, then set listenerGlobal's current event to event.if (!invocation_target_in_shadow_tree)- window->set_current_event(&event);+ listener_window->set_current_event(&event);}- // 9. If listener’s passive is true, then set event’s in passive listener flag.+ // 11. If listener’s passive is true, then set event’s in passive listener flag.if (listener->passive == true)event.set_in_passive_listener(true);- // FIXME: 10. If global is a Window object, then record timing info for event listener given event and listener.+ // FIXME: 12. If listenerGlobal is a Window object, then record timing info for event listener given event and listener.- // 11. Call a user object’s operation with listener’s callback, "handleEvent", « event », and event’s currentTarget attribute value.+ // 13. Call a user object’s operation with listener’s callback, "handleEvent", « event », and event’s currentTarget attribute value.auto result = Bindings::invoke_event_listener(callback, event);// If this throws an exception, then:@@ -110,14 +131,14 @@ bool EventDispatcher::inner_invoke(Event& event, EventTarget::ClonedEventListenelegacy_output_did_listeners_throw = true;}- // 12. Unset event’s in passive listener flag.+ // 14. Unset event’s in passive listener flag.event.set_in_passive_listener(false);- // 13. If global is a Window object, then set global’s current event to currentEvent.- if (window)- window->set_current_event(current_event);+ // 15. If listenerGlobal is a Window object, then set listenerGlobal's current event to currentEvent.+ if (listener_window)+ listener_window->set_current_event(current_event);- // 14. If event’s stop immediate propagation flag is set, then break.+ // 16. If event’s stop immediate propagation flag is set, then break.if (event.should_stop_immediate_propagation())break;}diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cppindex 15ecf95f89d..2304e128e2e 100644--- a/Libraries/LibWeb/DOM/EventTarget.cpp+++ b/Libraries/LibWeb/DOM/EventTarget.cpp@@ -146,6 +146,22 @@ HTML::Window* window_from_callback(WebIDL::CallbackType& callback)return HTML::window_from_global_object(realm.global_object());}+// targetGlobal in https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke for an event whose currentTarget isn't+// a node, if it's a Window: event's currentTarget's relevant global object.+DOM::EventTarget* current_target_global(WebIDL::CallbackType& callback, DOM::Event const& event)+{+ auto current_target = event.current_target();+ if (auto* window = as_if<HTML::Window>(current_target.ptr()))+ return window;++ // Any other target's relevant realm is its wrapper's: the realm it was created in.+ auto& callback_realm = callback.callback->shape().realm();+ auto wrapper = current_target_wrapper(callback_realm, event);+ if (!wrapper)+ return nullptr;+ return HTML::window_from_global_object(this_value_realm(callback_realm, wrapper).global_object());+}+void report_exception_for_callback(WebIDL::CallbackType& callback, JS::Value exception){auto& realm = callback.callback->shape().realm();@@ -926,18 +942,26 @@ void EventTarget::erase_all_event_listeners_and_handlers()// https://html.spec.whatwg.org/multipage/webappapis.html#the-event-handler-processing-algorithmJS::ThrowCompletionOr<void> EventTarget::process_event_handler_for_event(Utf16FlyString const& name, Event& event){- // 1. Let callback be the result of getting the current value of the event handler given eventTarget and name.+ // FIXME: 1. If the result of WebDriver BiDi scripting is enabled with eventTarget's relevant settings object is false,+ // then return.++ // 2. Let callback be the result of getting the current value of the event handler given eventTarget and name.auto* callback = get_current_value_of_event_handler(name);- // 2. If callback is null, then return.+ // 3. If callback is null, then return.if (!callback)return {};- // 3. Let special error event handling be true if event is an ErrorEvent object, event's type is error, and event's currentTarget implements the WindowOrWorkerGlobalScope mixin.+ // 4. If callback's associated realm's global object is a Window object whose associated Document is not fully+ // active, then return.+ if (auto* window = Bindings::window_from_callback(*callback); window && !window->associated_document().is_fully_active())+ return {};++ // 5. Let special error event handling be true if event is an ErrorEvent object, event's type is error, and event's currentTarget implements the WindowOrWorkerGlobalScope mixin.// Otherwise, let special error event handling be false.bool special_error_event_handling = is<HTML::ErrorEvent>(event) && event.type() == HTML::EventNames::error && is<HTML::WindowOrWorkerGlobalScopeMixin>(event.current_target().ptr());- // 4. Process the Event object event as follows:+ // 6. Process the Event object event as follows:JS::Completion return_value_or_error;return_value_or_error = Bindings::invoke_event_handler(*callback, event, special_error_event_handling);@@ -951,7 +975,7 @@ JS::ThrowCompletionOr<void> EventTarget::process_event_handler_for_event(Utf16Flauto is_beforeunload = event.type() == HTML::EventNames::beforeunload;- // 5. Process return value as follows:+ // 7. Process return value as follows:if (is<HTML::BeforeUnloadEvent>(event) && is_beforeunload) {// -> If event is a BeforeUnloadEvent object and event's type is "beforeunload"// If return value is not null, then:diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex cb2a0f6afa9..1d999af6506 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -1,4 +1,6 @@[LoadFromHttpServer]+Text/input/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.html+Text/input/wpt-import/dom/events/event-listener-not-fully-active-navigated.htmlCrash/DOM/shared-resource-request-finalize-while-in-flight.htmlText/input/css/linked-stylesheet-redirect-base-url.htmlText/input/HTML/initial-about-blank-window-outlives-abandoned-navigation.htmldiff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.txtnew file mode 100644index 00000000000..b938c3ee551--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 5 tests++5 Pass+Pass Node created in an iframe's realm and adopted into this document, iframe removed+Pass Node created in this realm and adopted into an iframe's document, iframe removed+Pass Adopting the target into a fully active iframe's document during dispatch+Pass Adopting the target into a removed iframe's document during dispatch+Pass Event from a node created in a removed iframe's realm still reaches listeners in this document\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-callback.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-callback.txtnew file mode 100644index 00000000000..c9442b93815--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-callback.txt@@ -0,0 +1,9 @@+Harness status: OK++Found 4 tests++4 Pass+Pass Function callback from a removed iframe, with a fully active target+Pass handleEvent() callback from a removed iframe, with a fully active target+Pass Event handler attribute set to a function from a removed iframe+Pass Listener added from a removed iframe, with a fully active target and callback\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-navigated.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-navigated.txtnew file mode 100644index 00000000000..5adc5e00f7c--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-navigated.txt@@ -0,0 +1,8 @@+Harness status: OK++Found 3 tests++3 Pass+Pass Targets in a document that its iframe has navigated away from+Pass Targets in a nested iframe whose parent document is no longer fully active+Pass Targets in a nested iframe whose parent iframe was removed\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-target.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-target.txtnew file mode 100644index 00000000000..1964d89388f--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/events/event-listener-not-fully-active-target.txt@@ -0,0 +1,21 @@+Harness status: OK++Found 16 tests++16 Pass+Pass EventTarget created in a removed iframe+Pass EventTarget created in a removed iframe, with an event from that iframe+Pass EventTarget created in a removed iframe, with a listener added after removal+Pass dispatchEvent() on an EventTarget in a removed iframe returns true+Pass Dispatch still happens for an EventTarget in a removed iframe, only the listeners are skipped+Pass handleEvent is not looked up for an EventTarget in a removed iframe+Pass Removing the iframe from within a listener skips the remaining listeners on the same target+Pass Removing the iframe during the capture phase skips the remaining objects in the event path+Pass Window of a removed iframe+Pass Document of a removed iframe+Pass Element of a removed iframe+Pass Event handler IDL attribute on an element in a removed iframe+Pass Compiled event handler content attribute on an element in a removed iframe+Pass AbortSignal from a removed iframe is still aborted+Pass Abort listeners on an AbortSignal from a removed iframe do not run+Pass It is the target's global that matters, not the event's\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/message-to-isolated-iframe-from-inactive-window-has-null-source.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/message-to-isolated-iframe-from-inactive-window-has-null-source.htmlindex b4e5c485bc9..c254e9c520b 100644--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/message-to-isolated-iframe-from-inactive-window-has-null-source.html+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/message-to-isolated-iframe-from-inactive-window-has-null-source.html@@ -2,8 +2,8 @@<script src="../../include.js"></script><script>// A window whose document is no longer active has no navigable to name it by in the isolated iframe's process, so- // a message it posts there arrives with a null source. The removed iframe's listener posts with its window as the- // incumbent.+ // a message it posts there arrives with a null source. A function from the removed iframe posts, which makes its+ // window the incumbent; an event listener from it wouldn't run at all.promiseTest(async () => {const remoteUrl = new URL(await httpTestServer().createEcho("GET", "/oop-message-from-inactive-window", {@@ -27,19 +27,20 @@const localIframe = document.createElement("iframe");localIframe.srcdoc = `<script>- parent.document.addEventListener("post", event => event.detail.postMessage("from a removed iframe", "*"));+ parent.postFromIframe = target => target.postMessage("from a removed iframe", "*");<\/script>`;await new Promise(resolve => {localIframe.onload = resolve;document.body.appendChild(localIframe);});const localWindow = localIframe.contentWindow;+ const { postFromIframe } = window;localIframe.remove();while (localWindow.parent !== null)await new Promise(resolve => setTimeout(resolve, 10));const reply = nextMessage();- document.dispatchEvent(new CustomEvent("post", { detail: remoteIframe.contentWindow }));+ postFromIframe(remoteIframe.contentWindow);const { data, sourceIsNull } = await reply;println(`data: ${data}`);println(`source is null: ${sourceIsNull}`);diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.html b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.htmlnew file mode 100644index 00000000000..07166008155--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-adopted-node.html@@ -0,0 +1,134 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Event listeners on nodes whose realm and node document disagree</title>+<link rel="help" href="https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke">+<link rel="help" href="https://github.com/whatwg/dom/issues/1084">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script src="resources/not-fully-active-helpers.js"></script>+<body>+<script>+"use strict";++// A node is created in the realm of the document it is created for, and+// adopting the node into another document does not change that realm. So for a+// node the realm it was created in and its node document can belong to+// different globals, which can independently stop being fully active.+//+// These tests assert that it is the node document's global that determines+// whether listeners run, matching how HTML defines "scripting is disabled" for+// a node.++const frameURL = "resources/not-fully-active-frame.html";++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const element = window.frameAPI.createElement();+ assert_false(element instanceof HTMLDivElement,+ "sanity check: the element was created in the iframe's realm");++ // Adopts the element into this document.+ document.body.append(element);+ t.add_cleanup(() => element.remove());++ let count = 0;+ element.addEventListener("x", () => count++);+ element.onclick = () => count++;++ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ assert_equals(count, 2, "listeners run while the iframe is attached");++ frame.remove();++ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ assert_equals(count, 4, "listeners still run once the iframe is removed");+}, "Node created in an iframe's realm and adopted into this document, iframe removed");++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const frameDocument = window.frameAPI.document;+ const element = document.createElement("div");++ // Adopts the element into the iframe's document.+ frameDocument.body.append(element);+ assert_true(element instanceof HTMLDivElement,+ "sanity check: adopting does not change the element's realm");++ let count = 0;+ element.addEventListener("x", () => count++);+ element.onclick = () => count++;++ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ assert_equals(count, 2, "listeners run while the iframe is attached");++ frame.remove();++ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ assert_equals(count, 2, "listeners do not run once the iframe is removed");+}, "Node created in this realm and adopted into an iframe's document, iframe removed");++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const frameDocument = window.frameAPI.document;+ const element = document.createElement("div");+ document.body.append(element);+ t.add_cleanup(() => element.remove());++ // Control for the test below: adopting the target into another fully active+ // document partway through dispatch does not stop the remaining listeners.+ const order = [];+ element.addEventListener("x", () => {+ order.push("first");+ frameDocument.body.append(element);+ });+ element.addEventListener("x", () => order.push("second"));++ element.dispatchEvent(new Event("x"));+ assert_array_equals(order, ["first", "second"]);+}, "Adopting the target into a fully active iframe's document during dispatch");++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const frameDocument = window.frameAPI.document;+ const element = document.createElement("div");+ document.body.append(element);+ t.add_cleanup(() => element.remove());++ // targetGlobal is determined per listener rather than once for the dispatch,+ // so adopting the target into a document that is no longer fully active+ // partway through does stop the remaining listeners.+ const order = [];+ element.addEventListener("x", () => {+ order.push("first");+ frameDocument.body.append(element);+ frame.remove();+ });+ element.addEventListener("x", () => order.push("second"));++ element.dispatchEvent(new Event("x"));+ assert_array_equals(order, ["first"]);+}, "Adopting the target into a removed iframe's document during dispatch");++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const element = window.frameAPI.createElement();+ document.body.append(element);+ t.add_cleanup(() => element.remove());++ // The listener is registered on an ancestor in this document, while the+ // target is a node from the removed iframe's realm.+ let count = 0;+ const listener = () => count++;+ document.body.addEventListener("x", listener);+ t.add_cleanup(() => document.body.removeEventListener("x", listener));++ frame.remove();++ element.dispatchEvent(new Event("x", { bubbles: true }));+ assert_equals(count, 1);+}, "Event from a node created in a removed iframe's realm still reaches listeners in this document");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-callback.html b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-callback.htmlnew file mode 100644index 00000000000..2c7b96ef04f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-callback.html@@ -0,0 +1,87 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Event listener callbacks from a document that is not fully active</title>+<link rel="help" href="https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke">+<link rel="help" href="https://html.spec.whatwg.org/#the-event-handler-processing-algorithm">+<link rel="help" href="https://github.com/whatwg/dom/issues/1084">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script src="resources/not-fully-active-helpers.js"></script>+<body>+<script>+"use strict";++// Separately from the event target's global, a listener is also not invoked+// when the global of its callback is a Window whose associated Document is not+// fully active — even when the target itself is fine. "Inner invoke" checks+// both globals, and the event handler processing algorithm checks the+// callback's global as well.+//+// What is *not* checked is the realm that addEventListener() happened to be+// called from.++promise_test(async t => {+ const frame = await addFrame(t, `<script>+ parent.callback = () => { parent.count++; };+ <\/script>`);+ const { callback } = window;+ window.count = 0;++ const target = new EventTarget();+ target.addEventListener("x", callback);++ target.dispatchEvent(new Event("x"));+ assert_equals(window.count, 1, "the callback runs while the iframe is attached");++ frame.remove();+ target.dispatchEvent(new Event("x"));+ assert_equals(window.count, 1, "the callback does not run once the iframe is removed");+}, "Function callback from a removed iframe, with a fully active target");++promise_test(async t => {+ const frame = await addFrame(t, `<script>+ parent.callbackObject = { handleEvent() { parent.count++; } };+ <\/script>`);+ const { callbackObject } = window;+ window.count = 0;++ const target = new EventTarget();+ target.addEventListener("x", callbackObject);+ frame.remove();++ target.dispatchEvent(new Event("x"));+ assert_equals(window.count, 0);+}, "handleEvent() callback from a removed iframe, with a fully active target");++promise_test(async t => {+ const frame = await addFrame(t, `<script>+ parent.callback = () => { parent.count++; };+ <\/script>`);+ const { callback } = window;+ window.count = 0;++ const element = document.createElement("div");+ element.onclick = callback;+ frame.remove();++ element.dispatchEvent(new Event("click"));+ assert_equals(window.count, 0);+}, "Event handler attribute set to a function from a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t, `<script>+ parent.addListener = (target, callback) => target.addEventListener("x", callback);+ <\/script>`);+ const { addListener } = window;++ // Both the target and the callback belong to this fully active document;+ // only addEventListener() was called from the iframe.+ const target = new EventTarget();+ let count = 0;+ addListener(target, () => count++);+ frame.remove();++ target.dispatchEvent(new Event("x"));+ assert_equals(count, 1);+}, "Listener added from a removed iframe, with a fully active target and callback");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-navigated.html b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-navigated.htmlnew file mode 100644index 00000000000..5c69a90c755--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-navigated.html@@ -0,0 +1,110 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Event listeners are not invoked for targets in a navigated-away-from document</title>+<link rel="help" href="https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke">+<link rel="help" href="https://github.com/whatwg/dom/issues/1084">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script src="resources/not-fully-active-helpers.js"></script>+<body>+<script>+"use strict";++// Removing an iframe is not the only way for a Document to stop being fully+// active: navigating away from it, or making one of its ancestors not fully+// active, has the same effect.+//+// Note that these tests deliberately avoid holding on to the iframe's+// WindowProxy across a navigation, since that would then refer to the new+// Window rather than to the old one.++const frameURL = "resources/not-fully-active-frame.html";++promise_test(async t => {+ const frame = await addSrcFrame(t, frameURL);+ const { document: doc, element, createEventTarget } = window.frameAPI;+ const target = createEventTarget();++ let count = 0;+ const listener = () => count++;+ doc.addEventListener("x", listener);+ element.addEventListener("x", listener);+ element.onclick = listener;+ target.addEventListener("x", listener);++ doc.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 4, "listeners run before the navigation");++ await navigateFrame(frame, "/common/blank.html");++ doc.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("click"));+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 4, "listeners do not run after the navigation");+}, "Targets in a document that its iframe has navigated away from");++promise_test(async t => {+ const outer = await addSrcFrame(t, "/common/blank.html");+ const outerDoc = outer.contentDocument;+ const inner = outerDoc.createElement("iframe");+ inner.src = new URL(frameURL, location.href).href;+ await new Promise(resolve => {+ inner.addEventListener("load", resolve, { once: true });+ outerDoc.body.append(inner);+ });++ const { document: doc, element, createEventTarget } = window.frameAPI;+ const target = createEventTarget();++ let count = 0;+ const listener = () => count++;+ doc.addEventListener("x", listener);+ element.addEventListener("x", listener);+ target.addEventListener("x", listener);++ doc.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("x"));+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 3, "listeners run while both iframes are attached");++ // This makes the outer document, and therefore the inner document, no longer+ // fully active.+ await navigateFrame(outer, "/common/blank.html?2");++ doc.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("x"));+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 3, "listeners do not run once the outer iframe navigated");+}, "Targets in a nested iframe whose parent document is no longer fully active");++promise_test(async t => {+ const outer = await addSrcFrame(t, "/common/blank.html");+ const outerDoc = outer.contentDocument;+ const inner = outerDoc.createElement("iframe");+ inner.src = new URL(frameURL, location.href).href;+ await new Promise(resolve => {+ inner.addEventListener("load", resolve, { once: true });+ outerDoc.body.append(inner);+ });++ const { document: doc, element, createEventTarget } = window.frameAPI;+ const target = createEventTarget();++ let count = 0;+ const listener = () => count++;+ doc.addEventListener("x", listener);+ element.addEventListener("x", listener);+ target.addEventListener("x", listener);++ outer.remove();++ doc.dispatchEvent(new Event("x"));+ element.dispatchEvent(new Event("x"));+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 0);+}, "Targets in a nested iframe whose parent iframe was removed");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-target.html b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-target.htmlnew file mode 100644index 00000000000..5d942d0f650--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/event-listener-not-fully-active-target.html@@ -0,0 +1,220 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Event listeners are not invoked when the target's document is not fully active</title>+<link rel="help" href="https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke">+<link rel="help" href="https://github.com/whatwg/dom/issues/1084">+<script src="../../resources/testharness.js"></script>+<script src="../../resources/testharnessreport.js"></script>+<script src="resources/not-fully-active-helpers.js"></script>+<body>+<script>+"use strict";++// "Inner invoke" skips a listener when the event target's global object is a+// Window whose associated Document is not fully active. Removing an iframe+// from the document tree destroys its Document, which makes that Document no+// longer fully active.++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ let count = 0;+ target.addEventListener("x", () => count++);++ target.dispatchEvent(new Event("x"));+ assert_equals(count, 1, "listener runs while the iframe is attached");++ frame.remove();+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 1, "listener does not run once the iframe is removed");+}, "EventTarget created in a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t, `<script>+ parent.target = new EventTarget();+ parent.frameEvent = new Event("x");+ <\/script>`);+ const { target, frameEvent } = window;+ let count = 0;+ target.addEventListener("x", () => count++);++ frame.remove();+ target.dispatchEvent(frameEvent);+ assert_equals(count, 0);+}, "EventTarget created in a removed iframe, with an event from that iframe");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ frame.remove();++ // The listener is added after the iframe was removed; it must not run+ // either.+ let count = 0;+ target.addEventListener("x", () => count++);+ target.dispatchEvent(new Event("x"));+ assert_equals(count, 0);+}, "EventTarget created in a removed iframe, with a listener added after removal");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ frame.remove();+ assert_true(target.dispatchEvent(new Event("x", { cancelable: true })));+}, "dispatchEvent() on an EventTarget in a removed iframe returns true");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ const event = new Event("x", { cancelable: true });+ target.addEventListener("x", e => e.preventDefault());+ frame.remove();++ // The dispatchEvent() return value is checked by the previous test; keeping+ // it out of this one means these assertions are still reached when an+ // implementation gets that wrong.+ target.dispatchEvent(event);+ assert_false(event.defaultPrevented, "defaultPrevented");+ assert_equals(event.target, target, "target");+ assert_equals(event.currentTarget, null, "currentTarget");+ assert_equals(event.eventPhase, Event.NONE, "eventPhase");+}, "Dispatch still happens for an EventTarget in a removed iframe, only the listeners are skipped");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ let accessed = false;+ target.addEventListener("x", { get handleEvent() { accessed = true; return () => {}; } });+ frame.remove();++ target.dispatchEvent(new Event("x"));+ assert_false(accessed);+}, "handleEvent is not looked up for an EventTarget in a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.target = new EventTarget();<\/script>`);+ const { target } = window;+ const order = [];+ target.addEventListener("x", () => { order.push("first"); frame.remove(); });+ target.addEventListener("x", () => order.push("second"));++ target.dispatchEvent(new Event("x"));+ assert_array_equals(order, ["first"]);+}, "Removing the iframe from within a listener skips the remaining listeners on the same target");++promise_test(async t => {+ const frame = await addFrame(t);+ const doc = frame.contentDocument;+ const element = doc.createElement("div");+ doc.body.append(element);++ const order = [];+ doc.addEventListener("x", () => { order.push("capture"); frame.remove(); }, true);+ element.addEventListener("x", () => order.push("target"));+ doc.addEventListener("x", () => order.push("bubble"));++ element.dispatchEvent(new Event("x", { bubbles: true }));+ assert_array_equals(order, ["capture"]);+}, "Removing the iframe during the capture phase skips the remaining objects in the event path");++promise_test(async t => {+ const frame = await addFrame(t);+ const win = frame.contentWindow;+ let count = 0;+ win.addEventListener("x", () => count++);+ frame.remove();++ win.dispatchEvent(new Event("x"));+ assert_equals(count, 0);+}, "Window of a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t);+ const doc = frame.contentDocument;+ let count = 0;+ doc.addEventListener("x", () => count++);+ frame.remove();++ doc.dispatchEvent(new Event("x"));+ assert_equals(count, 0);+}, "Document of a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t);+ const doc = frame.contentDocument;+ const element = doc.createElement("div");+ doc.body.append(element);+ let count = 0;+ element.addEventListener("x", () => count++);+ doc.addEventListener("x", () => count++);+ frame.remove();++ element.dispatchEvent(new Event("x", { bubbles: true }));+ assert_equals(count, 0);+}, "Element of a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t);+ const doc = frame.contentDocument;+ const element = doc.createElement("div");+ doc.body.append(element);++ let count = 0;+ element.onclick = () => count++;+ assert_equals(typeof element.onclick, "function", "the handler is set");+ frame.remove();++ element.dispatchEvent(new Event("click"));+ assert_equals(count, 0);+}, "Event handler IDL attribute on an element in a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t);+ const doc = frame.contentDocument;+ const element = doc.createElement("div");+ doc.body.append(element);+ t.add_cleanup(() => { delete window.contentAttributeHandlerRan; });++ element.setAttribute("onclick", "top.contentAttributeHandlerRan = true;");+ // Compile the handler while the iframe is still attached, so that this tests+ // the event handler processing algorithm rather than the compilation step.+ assert_equals(typeof element.onclick, "function", "the handler is compiled");+ frame.remove();++ element.dispatchEvent(new Event("click"));+ assert_equals(window.contentAttributeHandlerRan, undefined);+}, "Compiled event handler content attribute on an element in a removed iframe");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.controller = new AbortController();<\/script>`);+ const { controller } = window;+ frame.remove();++ controller.abort();+ assert_true(controller.signal.aborted);+}, "AbortSignal from a removed iframe is still aborted");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.controller = new AbortController();<\/script>`);+ const { controller } = window;+ let count = 0;+ controller.signal.addEventListener("abort", () => count++);+ controller.signal.onabort = () => count++;+ frame.remove();++ controller.abort();+ assert_equals(count, 0);+}, "Abort listeners on an AbortSignal from a removed iframe do not run");++promise_test(async t => {+ const frame = await addFrame(t, `<script>parent.frameEvent = new Event("x");<\/script>`);+ const { frameEvent } = window;+ const target = new EventTarget();+ let count = 0;+ target.addEventListener("x", () => count++);+ frame.remove();++ target.dispatchEvent(frameEvent);+ assert_equals(count, 1);+}, "It is the target's global that matters, not the event's");+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-frame.html b/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-frame.htmlnew file mode 100644index 00000000000..526bc935310--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-frame.html@@ -0,0 +1,18 @@+<!DOCTYPE html>+<meta charset="utf-8">+<title>Helper frame for the "not fully active" event listener tests</title>+<div id="target"></div>+<script>+"use strict";++// Everything here is created in this document's realm, for this document. The+// test document grabs what it needs before making this document not fully+// active. (This is exposed on top rather than parent as this frame is also+// used nested inside another frame.)+top.frameAPI = {+ document,+ element: document.getElementById("target"),+ createEventTarget: () => new EventTarget(),+ createElement: () => document.createElement("div"),+};+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-helpers.js b/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-helpers.jsnew file mode 100644index 00000000000..820fa01a8af--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/dom/events/resources/not-fully-active-helpers.js@@ -0,0 +1,37 @@+"use strict";++// Appends an iframe with the given srcdoc to the document and resolves with it+// once it has loaded. The iframe is removed again during cleanup (removing an+// already-removed iframe is a no-op).+globalThis.addFrame = (t, srcdoc = "") => {+ const frame = document.createElement("iframe");+ frame.srcdoc = srcdoc;+ return appendAndWait(t, frame);+};++// As above, but navigating to a URL, so that the iframe can be navigated again+// later. (Setting src on an iframe with a srcdoc attribute has no effect.)+globalThis.addSrcFrame = (t, src) => {+ const frame = document.createElement("iframe");+ frame.src = src;+ return appendAndWait(t, frame);+};++// Navigates an already-loaded iframe and resolves once the new document has+// loaded.+globalThis.navigateFrame = (frame, url) => {+ const loaded = new Promise(resolve => {+ frame.addEventListener("load", resolve, { once: true });+ });+ frame.src = url;+ return loaded;+};++function appendAndWait(t, frame) {+ const loaded = new Promise(resolve => {+ frame.addEventListener("load", resolve, { once: true });+ });+ t.add_cleanup(() => frame.remove());+ document.body.append(frame);+ return loaded.then(() => frame);+}