1 /*
2 * Copyright (c) 2002-2026 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.javascript.host.event;
16
17 import java.io.IOException;
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import org.apache.commons.lang3.StringUtils;
22 import org.htmlunit.Page;
23 import org.htmlunit.ScriptResult;
24 import org.htmlunit.corejs.javascript.Function;
25 import org.htmlunit.corejs.javascript.Scriptable;
26 import org.htmlunit.html.DomElement;
27 import org.htmlunit.html.DomNode;
28 import org.htmlunit.html.HtmlElement;
29 import org.htmlunit.html.HtmlLabel;
30 import org.htmlunit.javascript.HtmlUnitScriptable;
31 import org.htmlunit.javascript.JavaScriptEngine;
32 import org.htmlunit.javascript.configuration.JsxClass;
33 import org.htmlunit.javascript.configuration.JsxConstructor;
34 import org.htmlunit.javascript.configuration.JsxFunction;
35 import org.htmlunit.javascript.host.Window;
36 import org.htmlunit.javascript.host.dom.Document;
37
38 /**
39 * JavaScript host object for {@code EventTarget}.
40 *
41 * @author Ahmed Ashour
42 * @author Ronald Brill
43 * @author Atsushi Nakagawa
44 *
45 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">MDN Documentation</a>
46 */
47 @JsxClass
48 public class EventTarget extends HtmlUnitScriptable {
49
50 private EventListenersContainer eventListenersContainer_;
51
52 /**
53 * Creates an instance of this object.
54 */
55 @JsxConstructor
56 public void jsConstructor() {
57 // nothing to do
58 }
59
60 /**
61 * Registers an event listener on this event target.
62 *
63 * @param type the event type to listen for (e.g. {@code "click"})
64 * @param listener the event listener
65 * @param useCapture if {@code true}, indicates that the listener should be added for the capture phase
66 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">MDN Documentation</a>
67 */
68 @JsxFunction
69 public void addEventListener(final String type, final Scriptable listener, final boolean useCapture) {
70 getEventListenersContainer().addEventListener(type, listener, useCapture);
71 }
72
73 /**
74 * Returns the container for event listeners, creating it if necessary.
75 *
76 * @return the event listeners container
77 */
78 public final EventListenersContainer getEventListenersContainer() {
79 if (eventListenersContainer_ == null) {
80 eventListenersContainer_ = new EventListenersContainer(this);
81 }
82 return eventListenersContainer_;
83 }
84
85 /**
86 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
87 * Removes all event listeners and event handlers of this event target
88 * (e.g. done by document.open()).
89 */
90 public void removeAllEventListeners() {
91 eventListenersContainer_ = null;
92 }
93
94 /**
95 * Executes the event on this object only (needed for instance for {@code onload} on {@code (i)frame} tags).
96 *
97 * @param event the event to execute
98 * @see #fireEvent(Event)
99 */
100 public void executeEventLocally(final Event event) {
101 final EventListenersContainer eventListenersContainer = getEventListenersContainer();
102 final Window window = getWindowIfAvailable();
103 final Object[] args = {event};
104
105 final Event previousEvent = window == null ? null : window.getCurrentEvent();
106 if (window != null) {
107 window.setCurrentEvent(event);
108 }
109 try {
110 event.setEventPhase(Event.AT_TARGET);
111 eventListenersContainer.executeAtTargetListeners(event, args);
112 }
113 finally {
114 if (window != null) {
115 window.setCurrentEvent(previousEvent); // reset event
116 }
117 }
118 }
119
120 /**
121 * Returns the window of this object; {@code null} for objects of a worker.
122 *
123 * @return the window or {@code null}
124 */
125 private Window getWindowIfAvailable() {
126 if (getWindowOrWorkerGlobalScope(this) instanceof Window window) {
127 return window;
128 }
129 return null;
130 }
131
132 /**
133 * Fires the event on this node with capturing and bubbling phases.
134 *
135 * @param event the event to fire
136 * @return the script result
137 */
138 public ScriptResult fireEvent(final Event event) {
139 // null inside of workers
140 final Window window = getWindowIfAvailable();
141
142 event.startFire();
143 final Event previousEvent = window == null ? null : window.getCurrentEvent();
144 if (window != null) {
145 window.setCurrentEvent(event);
146 }
147
148 try {
149 // These can be null if we aren't tied to a DOM node
150 final DomNode ourNode = getDomNodeOrNull();
151 final DomNode ourParentNode = (ourNode != null) ? ourNode.getParentNode() : null;
152
153 // Determine the propagation path which is fixed here and not affected by
154 // DOM tree modification from intermediate listeners (tested in Chrome)
155 final List<EventTarget> propagationPath = new ArrayList<>();
156
157 // We're added to the propagation path first
158 propagationPath.add(this);
159
160 // Then add all our parents if we have any (pure JS object such as XMLHttpRequest
161 // and MessagePort, etc. will not have any parents)
162 for (DomNode parent = ourParentNode; parent != null; parent = parent.getParentNode()) {
163 // scroll does not bubble into the document/window
164 if (Event.TYPE_SCROLL.equals(event.getType()) && parent instanceof Page) {
165 break;
166 }
167
168 propagationPath.add(parent.getScriptableObject());
169 }
170
171 // The load event has some unnatural behavior that we need to handle specially
172 // The load event for other elements target that element but path only
173 // up to Document and not Window, so do nothing here
174 // (see Note in https://www.w3.org/TR/DOM-Level-3-Events/#event-type-load)
175 if (!Event.TYPE_LOAD.equals(event.getType())) {
176 // Add Window if the propagation path reached Document
177 if (window != null && propagationPath.get(propagationPath.size() - 1) instanceof Document) {
178 propagationPath.add(window);
179 }
180 }
181
182 // capturing phase
183 event.setEventPhase(Event.CAPTURING_PHASE);
184
185 for (int i = propagationPath.size() - 1; i >= 1; i--) {
186 final EventTarget jsNode = propagationPath.get(i);
187 final EventListenersContainer elc = jsNode.eventListenersContainer_;
188 if (elc != null) {
189 elc.executeCapturingListeners(event, new Object[] {event});
190 if (event.isPropagationStopped()) {
191 return new ScriptResult(null);
192 }
193 }
194 }
195
196 // at target phase
197 event.setEventPhase(Event.AT_TARGET);
198
199 if (!propagationPath.isEmpty()) {
200 // Note: This element is not always the same as event.getTarget():
201 // e.g. the 'load' event targets Document but "at target" is on Window.
202 final EventTarget jsNode = propagationPath.get(0);
203 final EventListenersContainer elc = jsNode.eventListenersContainer_;
204 if (elc != null) {
205 elc.executeAtTargetListeners(event, new Object[] {event});
206 if (event.isPropagationStopped()) {
207 return new ScriptResult(null);
208 }
209 }
210 }
211
212 // bubbling phase
213 if (event.isBubbles()) {
214 // This belongs here inside the block because events that don't bubble never set
215 // eventPhase = 3 (tested in Chrome)
216 event.setEventPhase(Event.BUBBLING_PHASE);
217
218 final int size = propagationPath.size();
219 for (int i = 1; i < size; i++) {
220 final EventTarget jsNode = propagationPath.get(i);
221 final EventListenersContainer elc = jsNode.eventListenersContainer_;
222 if (elc != null) {
223 elc.executeBubblingListeners(event, new Object[] {event});
224 if (event.isPropagationStopped()) {
225 return new ScriptResult(null);
226 }
227 }
228 }
229 }
230
231 HtmlLabel label = null;
232 if (event.processLabelAfterBubbling()) {
233 for (DomNode parent = ourParentNode; parent != null; parent = parent.getParentNode()) {
234 if (parent instanceof HtmlLabel htmlLabel) {
235 label = htmlLabel;
236 break;
237 }
238 }
239 }
240
241 if (label != null) {
242 final HtmlElement element = label.getLabeledElement();
243 if (element != null && element != getDomNodeOrNull()) {
244 try {
245 element.click(event.isShiftKey(), event.isCtrlKey(), event.isAltKey(), false, true, true, true);
246 }
247 catch (final IOException ignored) {
248 // ignore for now
249 }
250 }
251 }
252
253 }
254 finally {
255 event.endFire();
256 if (window != null) {
257 window.setCurrentEvent(previousEvent); // reset event
258 }
259 }
260
261 return new ScriptResult(null);
262 }
263
264 /**
265 * Returns whether there are any event handlers for the specified event name.
266 *
267 * @param eventName the event name (e.g. {@code "onclick"})
268 * @return {@code true} if there are any event handlers, {@code false} otherwise
269 */
270 public boolean hasEventHandlers(final String eventName) {
271 if (eventListenersContainer_ == null) {
272 return false;
273 }
274 return eventListenersContainer_.hasEventListeners(StringUtils.substring(eventName, 2));
275 }
276
277 /**
278 * Returns the specified event handler function.
279 *
280 * @param eventType the event type (e.g. {@code "click"})
281 * @return the handler function, or {@code null} if not set
282 */
283 public Function getEventHandler(final String eventType) {
284 if (eventListenersContainer_ == null) {
285 return null;
286 }
287 return eventListenersContainer_.getEventHandler(eventType);
288 }
289
290 /**
291 * Dispatches an event into the event system.
292 *
293 * @param event the event to be dispatched
294 * @return {@code false} if at least one of the event handlers called {@code preventDefault()};
295 * {@code true} otherwise
296 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent">MDN Documentation</a>
297 */
298 @JsxFunction
299 public boolean dispatchEvent(final Event event) {
300 event.setTarget(this);
301
302 ScriptResult result = null;
303 final DomNode domNode = getDomNodeOrNull();
304 if (MouseEvent.TYPE_CLICK.equals(event.getType()) && (domNode instanceof DomElement element)) {
305 try {
306 element.click(event, event.isShiftKey(), event.isCtrlKey(), event.isAltKey(), true);
307 }
308 catch (final IOException e) {
309 throw JavaScriptEngine.reportRuntimeError("Error calling click(): " + e.getMessage());
310 }
311 }
312 else {
313 result = fireEvent(event);
314 }
315 return !event.isAborted(result);
316 }
317
318 /**
319 * Removes a previously registered event listener from this event target.
320 *
321 * @param type the event type (e.g. {@code "click"})
322 * @param listener the listener to remove
323 * @param useCapture if {@code true}, the listener is removed from the capture phase
324 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener">MDN Documentation</a>
325 */
326 @JsxFunction
327 public void removeEventListener(final String type, final Scriptable listener, final boolean useCapture) {
328 if (eventListenersContainer_ == null) {
329 return;
330 }
331 eventListenersContainer_.removeEventListener(type, listener, useCapture);
332 }
333
334 /**
335 * Defines an event handler (or any other object) for the given event name.
336 *
337 * @param eventName the event name (e.g. {@code "click"})
338 * @param value the handler ({@code null} to reset it)
339 */
340 public void setEventHandler(final String eventName, final Object value) {
341 if (isEventHandlerOnWindow()) {
342 getWindow().getEventListenersContainer().setEventHandler(eventName, value);
343 return;
344 }
345 getEventListenersContainer().setEventHandler(eventName, value);
346 }
347
348 /**
349 * Returns whether the event handler property should be set at the window level.
350 *
351 * @return {@code true} if the event handler should be set at window level
352 */
353 protected boolean isEventHandlerOnWindow() {
354 return false;
355 }
356
357 /**
358 * Clears the event listener container.
359 */
360 protected void clearEventListenersContainer() {
361 eventListenersContainer_ = null;
362 }
363 }