View Javadoc
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.html;
16  
17  import static org.htmlunit.BrowserVersionFeatures.EVENT_FOCUS_ON_LOAD;
18  import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_CH_UA;
19  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  import java.io.Serializable;
26  import java.net.MalformedURLException;
27  import java.net.URL;
28  import java.nio.charset.Charset;
29  import java.nio.charset.StandardCharsets;
30  import java.util.ArrayList;
31  import java.util.Arrays;
32  import java.util.Collection;
33  import java.util.Collections;
34  import java.util.Comparator;
35  import java.util.HashMap;
36  import java.util.HashSet;
37  import java.util.Iterator;
38  import java.util.LinkedHashSet;
39  import java.util.List;
40  import java.util.Locale;
41  import java.util.Map;
42  import java.util.Set;
43  import java.util.WeakHashMap;
44  import java.util.concurrent.ConcurrentHashMap;
45  import java.util.concurrent.atomic.AtomicInteger;
46  
47  import javax.xml.XMLConstants;
48  
49  import org.apache.commons.lang3.StringUtils;
50  import org.apache.commons.logging.Log;
51  import org.apache.commons.logging.LogFactory;
52  import org.htmlunit.Cache;
53  import org.htmlunit.ElementNotFoundException;
54  import org.htmlunit.FailingHttpStatusCodeException;
55  import org.htmlunit.History;
56  import org.htmlunit.HttpHeader;
57  import org.htmlunit.OnbeforeunloadHandler;
58  import org.htmlunit.Page;
59  import org.htmlunit.ReferrerPolicy;
60  import org.htmlunit.ScriptResult;
61  import org.htmlunit.SgmlPage;
62  import org.htmlunit.StringWebResponse;
63  import org.htmlunit.TopLevelWindow;
64  import org.htmlunit.WebAssert;
65  import org.htmlunit.WebClient;
66  import org.htmlunit.WebClientOptions;
67  import org.htmlunit.WebRequest;
68  import org.htmlunit.WebResponse;
69  import org.htmlunit.WebWindow;
70  import org.htmlunit.corejs.javascript.Function;
71  import org.htmlunit.corejs.javascript.Script;
72  import org.htmlunit.corejs.javascript.Scriptable;
73  import org.htmlunit.corejs.javascript.ScriptableObject;
74  import org.htmlunit.corejs.javascript.VarScope;
75  import org.htmlunit.css.ComputedCssStyleDeclaration;
76  import org.htmlunit.css.CssStyleSheet;
77  import org.htmlunit.html.csp.ContentSecurityPolicy;
78  import org.htmlunit.html.impl.SimpleRange;
79  import org.htmlunit.html.parser.HTMLParserDOMBuilder;
80  import org.htmlunit.http.HttpStatus;
81  import org.htmlunit.javascript.AbstractJavaScriptEngine;
82  import org.htmlunit.javascript.HtmlUnitScriptable;
83  import org.htmlunit.javascript.JavaScriptEngine;
84  import org.htmlunit.javascript.PostponedAction;
85  import org.htmlunit.javascript.background.BackgroundJavaScriptFactory;
86  import org.htmlunit.javascript.background.JavaScriptJob;
87  import org.htmlunit.javascript.host.Window;
88  import org.htmlunit.javascript.host.event.BeforeUnloadEvent;
89  import org.htmlunit.javascript.host.event.Event;
90  import org.htmlunit.javascript.host.event.EventTarget;
91  import org.htmlunit.javascript.host.html.HTMLDocument;
92  import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
93  import org.htmlunit.util.MimeType;
94  import org.htmlunit.util.NameValuePair;
95  import org.htmlunit.util.SerializableLock;
96  import org.htmlunit.util.UrlUtils;
97  import org.w3c.dom.Attr;
98  import org.w3c.dom.Comment;
99  import org.w3c.dom.DOMConfiguration;
100 import org.w3c.dom.DOMException;
101 import org.w3c.dom.DOMImplementation;
102 import org.w3c.dom.Document;
103 import org.w3c.dom.DocumentType;
104 import org.w3c.dom.Element;
105 import org.w3c.dom.EntityReference;
106 import org.w3c.dom.ProcessingInstruction;
107 
108 /**
109  * A representation of an HTML page returned from a server.
110  * <p>
111  * This class provides different methods to access the page's content like
112  * {@link #getForms()}, {@link #getAnchors()}, {@link #getElementById(String)}, ... as well as the
113  * very powerful inherited methods {@link #getByXPath(String)} and {@link #getFirstByXPath(String)}
114  * for fine grained user specific access to child nodes.
115  * </p>
116  * <p>
117  * Child elements allowing user interaction provide methods for this purpose like {@link HtmlAnchor#click()},
118  * {@link HtmlInput#type(String)}, {@link HtmlOption#setSelected(boolean)}, ...
119  * </p>
120  * <p>
121  * HtmlPage instances should not be instantiated directly. They will be returned by {@link WebClient#getPage(String)}
122  * when the content type of the server's response is <code>text/html</code> (or one of its variations).<br>
123  * <br>
124  * <b>Example:</b><br>
125  * <br>
126  * <code>
127  * final HtmlPage page = webClient.{@link WebClient#getPage(String) getPage}("http://mywebsite/some/page.html");
128  * </code>
129  * </p>
130  *
131  * @author Mike Bowler
132  * @author Alex Nikiforoff
133  * @author Noboru Sinohara
134  * @author David K. Taylor
135  * @author Andreas Hangler
136  * @author Christian Sell
137  * @author Chris Erskine
138  * @author Marc Guillemot
139  * @author Ahmed Ashour
140  * @author Daniel Gredler
141  * @author Dmitri Zoubkov
142  * @author Sudhan Moghe
143  * @author Ethan Glasser-Camp
144  * @author Tom Anderson
145  * @author Ronald Brill
146  * @author Frank Danek
147  * @author Joerg Werner
148  * @author Atsushi Nakagawa
149  * @author Rural Hunter
150  * @author Ronny Shapiro
151  * @author Lai Quang Duong
152  * @author Sven Strickroth
153  * @author Vidya m
154  */
155 @SuppressWarnings("PMD.TooManyFields")
156 public class HtmlPage extends SgmlPage {
157 
158     private static final Log LOG = LogFactory.getLog(HtmlPage.class);
159 
160     private static final Comparator<DomElement> DOCUMENT_POSITION_COMPERATOR = new DocumentPositionComparator();
161 
162     private HTMLParserDOMBuilder domBuilder_;
163     private transient Charset originalCharset_;
164     private final Object lock_ = new SerializableLock(); // used for synchronization
165 
166     private Map<String, MappedElementIndexEntry> idMap_ = new ConcurrentHashMap<>();
167     private Map<String, MappedElementIndexEntry> nameMap_ = new ConcurrentHashMap<>();
168     // The id/name lookup index is built lazily on first use. Until then,
169     // notifyNodeAdded / fireAttributeChange skip the per-element index updates.
170     // Reads must call ensureMappedElementsBuilt() before consulting idMap_/nameMap_.
171     // volatile: other threads have to see the flag not before the populated maps
172     private volatile boolean mappedElementsBuilt_;
173 
174     private List<BaseFrameElement> frameElements_ = new ArrayList<>();
175     // a parser may run on the loading thread and on the JavaScript thread (e.g. innerHTML in a timer)
176     private AtomicInteger parserCount_ = new AtomicInteger();
177     // the snippet parsing (innerHTML, document.write()...) is done by the thread of the script, therefore
178     // the state is per thread; otherwise the loading thread parses the page as snippet (e.g. without running
179     // the scripts) while the JavaScript thread runs a timer that sets innerHTML
180     private transient ThreadLocal<SnippetParserCount> snippetParserCount_ = new ThreadLocal<>();
181     private Collection<HtmlAttributeChangeListener> attributeListeners_;
182     private List<PostponedAction> afterLoadActions_ = Collections.synchronizedList(new ArrayList<>());
183     private boolean cleaning_;
184     private HtmlBase base_;
185     private URL baseUrl_;
186     // the href of the base element checked against the Content-Security-Policy (base-uri) and the result
187     private String cspCheckedBaseHref_;
188     private boolean cspBaseAllowed_ = true;
189     private List<AutoCloseable> autoCloseableList_;
190     private ElementFromPointHandler elementFromPointHandler_;
191     private DomElement elementWithFocus_;
192     private List<SimpleRange> selectionRanges_ = new ArrayList<>(3);
193 
194     // the elements with an autofocus attribute inserted into this page (in insertion order)
195     private List<HtmlElement> autofocusCandidates_;
196     // true if the autofocus was already processed; the autofocus is only used once per page
197     private boolean autofocusProcessed_;
198 
199     private ContentSecurityPolicy contentSecurityPolicy_;
200     // the referrer policy of this document (Referrer-Policy header, meta element); null for the default
201     private ReferrerPolicy referrerPolicy_;
202     // the sandbox tokens (allowed features) of this document; null if not sandboxed
203     private Set<String> sandboxTokens_;
204     // true if the page is loaded; candidates inserted later are processed by a job
205     private boolean autofocusAfterLoad_;
206     private boolean autofocusJobScheduled_;
207 
208     private transient ComputedStylesCache computedStylesCache_;
209 
210     private static final HashSet<String> TABBABLE_TAGS =
211             new HashSet<>(Arrays.asList(HtmlAnchor.TAG_NAME, HtmlArea.TAG_NAME,
212                     HtmlButton.TAG_NAME, HtmlInput.TAG_NAME, HtmlObject.TAG_NAME,
213                     HtmlSelect.TAG_NAME, HtmlTextArea.TAG_NAME));
214     private static final HashSet<String> ACCEPTABLE_TAG_NAMES =
215             new HashSet<>(Arrays.asList(HtmlAnchor.TAG_NAME, HtmlArea.TAG_NAME,
216                     HtmlButton.TAG_NAME, HtmlInput.TAG_NAME, HtmlLabel.TAG_NAME,
217                     HtmlLegend.TAG_NAME, HtmlTextArea.TAG_NAME));
218 
219     /** Definition of special cases for the smart DomHtmlAttributeChangeListenerImpl. */
220     private static final Set<String> ATTRIBUTES_AFFECTING_PARENT = new HashSet<>(Arrays.asList(
221             "style",
222             "class",
223             "height",
224             "width"));
225 
226     static class DocumentPositionComparator implements Comparator<DomElement>, Serializable {
227         @Override
228         public int compare(final DomElement elt1, final DomElement elt2) {
229             final short relation = elt1.compareDocumentPosition(elt2);
230             if (relation == 0) {
231                 return 0; // same node
232             }
233             if ((relation & DOCUMENT_POSITION_CONTAINS) != 0 || (relation & DOCUMENT_POSITION_PRECEDING) != 0) {
234                 return 1;
235             }
236 
237             return -1;
238         }
239     }
240 
241     /**
242      * Creates an instance of HtmlPage.
243      * An HtmlPage instance is normally retrieved with {@link WebClient#getPage(String)}.
244      *
245      * @param webResponse the web response that was used to create this page
246      * @param webWindow the window that this page is being loaded into
247      */
248     public HtmlPage(final WebResponse webResponse, final WebWindow webWindow) {
249         super(webResponse, webWindow);
250         if (webWindow instanceof FrameWindow frameWindow) {
251             sandboxTokens_ = frameWindow.getSandboxTokens();
252         }
253         contentSecurityPolicy_ = ContentSecurityPolicy.fromResponse(webResponse);
254         if (contentSecurityPolicy_ == null && webResponse != null) {
255             // the content written by document.open()/write()/close() and the result of a
256             // javascript: url replace the current document; the policy is kept
257             if (webResponse instanceof StringWebResponse stringWebResponse
258                     && stringWebResponse.isFromJavascript()
259                     && webWindow != null
260                     && webWindow.getEnclosedPage() instanceof HtmlPage currentPage) {
261                 contentSecurityPolicy_ = currentPage.getContentSecurityPolicy();
262             }
263             else {
264                 contentSecurityPolicy_ = ContentSecurityPolicy.inherit(webResponse.getWebRequest().getUrl(),
265                                             webWindow);
266             }
267         }
268 
269         // the sandbox directive of an enforced policy delivered by a header sandboxes the document
270         // (in addition to the sandbox attribute of the iframe)
271         if (contentSecurityPolicy_ != null) {
272             final Set<String> cspSandboxTokens = contentSecurityPolicy_.getSandboxTokens();
273             if (cspSandboxTokens != null) {
274                 if (sandboxTokens_ == null) {
275                     sandboxTokens_ = cspSandboxTokens;
276                 }
277                 else {
278                     final Set<String> tokens = new HashSet<>(sandboxTokens_);
279                     tokens.retainAll(cspSandboxTokens);
280                     sandboxTokens_ = tokens;
281                 }
282             }
283         }
284 
285         referrerPolicy_ = referrerPolicyFromResponse(webResponse);
286         if (referrerPolicy_ == null && webWindow != null) {
287             // like the Content-Security-Policy: the content written by document.open()/write()/close()
288             // keeps the policy, about:blank and about:srcdoc documents of frames have the one of the parent
289             if (webResponse instanceof StringWebResponse stringWebResponse
290                     && stringWebResponse.isFromJavascript()
291                     && webWindow.getEnclosedPage() instanceof HtmlPage currentPage) {
292                 referrerPolicy_ = currentPage.referrerPolicy_;
293             }
294             else if (webResponse != null
295                     && "about".equals(webResponse.getWebRequest().getUrl().getProtocol())
296                     && webWindow instanceof FrameWindow frameWindow
297                     && frameWindow.getEnclosingPage() != null) {
298                 referrerPolicy_ = frameWindow.getEnclosingPage().referrerPolicy_;
299             }
300         }
301     }
302 
303     /**
304      * Returns the policy of the Referrer-Policy header(s) of the response.
305      *
306      * @param webResponse the response
307      * @return the policy or {@code null} if there is no (valid) header
308      */
309     private static ReferrerPolicy referrerPolicyFromResponse(final WebResponse webResponse) {
310         if (webResponse == null) {
311             return null;
312         }
313         final StringBuilder value = new StringBuilder();
314         for (final NameValuePair header : webResponse.getResponseHeaders()) {
315             if (HttpHeader.REFERRER_POLICY.equalsIgnoreCase(header.getName())) {
316                 if (value.length() > 0) {
317                     value.append(',');
318                 }
319                 value.append(header.getValue());
320             }
321         }
322         return ReferrerPolicy.fromHeader(value.toString());
323     }
324 
325     /**
326      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
327      *
328      * Returns the referrer policy of this document (from the Referrer-Policy header or a
329      * meta element with the name 'referrer').
330      *
331      * @return the referrer policy, {@link ReferrerPolicy#DEFAULT} if not set
332      */
333     public ReferrerPolicy getReferrerPolicy() {
334         return referrerPolicy_ == null ? ReferrerPolicy.DEFAULT : referrerPolicy_;
335     }
336 
337     /**
338      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
339      *
340      * Returns the referrer policy for a request of the given element: the policy of the
341      * referrerpolicy attribute of the element if valid, otherwise the policy of this document.
342      *
343      * @param element the element
344      * @return the referrer policy
345      */
346     public ReferrerPolicy getReferrerPolicy(final DomElement element) {
347         final ReferrerPolicy policy = ReferrerPolicy.fromToken(element.getAttributeDirect("referrerpolicy"));
348         if (policy != null) {
349             return policy;
350         }
351         return getReferrerPolicy();
352     }
353 
354     /**
355      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
356      *
357      * Sets the referrer policy of this document (e.g. from a meta element).
358      *
359      * @param referrerPolicy the referrer policy
360      */
361     public void setReferrerPolicy(final ReferrerPolicy referrerPolicy) {
362         referrerPolicy_ = referrerPolicy;
363     }
364 
365     /**
366      * {@inheritDoc}
367      */
368     @Override
369     public HtmlPage getPage() {
370         return this;
371     }
372 
373     /**
374      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
375      *
376      * Returns the Content-Security-Policy of this page.
377      *
378      * @return the policy or {@code null} if this page has no policy
379      */
380     public ContentSecurityPolicy getContentSecurityPolicy() {
381         return contentSecurityPolicy_;
382     }
383 
384     /**
385      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
386      *
387      * Returns the url used to determine the origin of this page. Like in the browsers, an about:blank
388      * document has the origin of its creator; for frames this is the parent document, for windows
389      * opened by window.open() the opener. For all other pages this is the url of the page.
390      *
391      * @return the url of the origin
392      */
393     public URL getOriginUrl() {
394         final URL url = getUrl();
395         final String urlString = url.toExternalForm();
396         // about:blank and about:srcdoc documents have the origin of the creator (parent)
397         if (!UrlUtils.ABOUT_BLANK.equals(urlString) && !UrlUtils.ABOUT_SRCDOC.equals(urlString)) {
398             return url;
399         }
400 
401         final WebWindow window = getEnclosingWindow();
402         WebWindow creator = null;
403         if (window instanceof FrameWindow) {
404             creator = window.getParentWindow();
405         }
406         else if (window instanceof TopLevelWindow topLevelWindow) {
407             creator = topLevelWindow.getOpener();
408         }
409         if (creator != null && creator != window && creator.getEnclosedPage() instanceof HtmlPage creatorPage) {
410             return creatorPage.getOriginUrl();
411         }
412         return url;
413     }
414 
415     /**
416      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
417      *
418      * Determines whether this page is allowed to load the specified URL (e.g. into a frame or a window).
419      * Like in the browsers, only pages from a file are allowed to load local resources (file URLs);
420      * about:blank and about:srcdoc documents are judged by the origin of their creator
421      * (see {@link #getOriginUrl()}).
422      * This check can be disabled with
423      * {@link org.htmlunit.WebClientOptions#setLocalFileAccessFromRemotePagesAllowed(boolean)}.
424      *
425      * @param url the URL to load
426      * @return {@code false} if the URL is a file URL and this page does not have a file origin
427      */
428     public boolean isLocalResourceAccessAllowed(final URL url) {
429         if (getWebClient().getOptions().isLocalFileAccessFromRemotePagesAllowed()) {
430             return true;
431         }
432         return UrlUtils.isLocalResourceAccessAllowed(getOriginUrl(), url);
433     }
434 
435     /**
436      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
437      *
438      * Returns the sandbox tokens (the allowed features, e.g. 'allow-scripts') of this document;
439      * the document of an iframe with sandbox attribute is sandboxed.
440      *
441      * @return the tokens or {@code null} if this document is not sandboxed
442      */
443     public Set<String> getSandboxTokens() {
444         return sandboxTokens_;
445     }
446 
447     /**
448      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
449      *
450      * Returns whether the feature is allowed for this document; all features are allowed if this
451      * document is not sandboxed.
452      *
453      * @param token the token of the feature (e.g. 'allow-scripts')
454      * @return true if the feature is allowed
455      * @see <a href="https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox">
456      *     HTML Living Standard - sandbox</a>
457      */
458     public boolean isSandboxAllowed(final String token) {
459         return sandboxTokens_ == null || sandboxTokens_.contains(token);
460     }
461 
462     /**
463      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
464      *
465      * Returns whether this document has an opaque origin: a sandboxed document without 'allow-same-origin'.
466      * Such a document has no access to the cookies and the storage.
467      *
468      * @return true if the origin is opaque
469      */
470     public boolean isOpaqueOrigin() {
471         return sandboxTokens_ != null && !sandboxTokens_.contains("allow-same-origin");
472     }
473 
474     /**
475      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
476      *
477      * Returns the url of the 'site for cookies' of this document: the url of the top-level
478      * document if this document and all its ancestors are same-site with it, otherwise
479      * 'about:blank' (no site, never same-site with any url). A document without a window
480      * (e.g. created by DOMImplementation.createHTMLDocument() or DOMParser) uses its own origin.
481      *
482      * @return the url of the site for cookies
483      * @see <a href="https://html.spec.whatwg.org/multipage/browsers.html#site-for-cookies">site for cookies</a>
484      */
485     public URL getSiteForCookiesUrl() {
486         final WebWindow window = getEnclosingWindow();
487         if (window == null) {
488             return getOriginUrl();
489         }
490         final WebWindow top = window.getTopWindow();
491         if (!(top.getEnclosedPage() instanceof HtmlPage topPage)) {
492             return getOriginUrl();
493         }
494 
495         final URL topUrl = topPage.getOriginUrl();
496         WebWindow current = window;
497         while (current != null && current != top) {
498             if (current.getEnclosedPage() instanceof HtmlPage currentPage
499                     && !WebClient.isSameSite(currentPage.getOriginUrl(), topUrl)) {
500                 return UrlUtils.URL_ABOUT_BLANK;
501             }
502             current = current.getParentWindow();
503         }
504         return topUrl;
505     }
506 
507     /**
508      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
509      *
510      * Sets the Content-Security-Policy of this page.
511      *
512      * @param contentSecurityPolicy the policy
513      */
514     public void setContentSecurityPolicy(final ContentSecurityPolicy contentSecurityPolicy) {
515         contentSecurityPolicy_ = contentSecurityPolicy;
516     }
517 
518     /**
519      * {@inheritDoc}
520      */
521     @Override
522     public boolean hasCaseSensitiveTagNames() {
523         return false;
524     }
525 
526     /**
527      * Initialize this page.
528      * @throws IOException if an IO problem occurs
529      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
530      *         {@link org.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set
531      *         to true.
532      */
533     @Override
534     public void initialize() throws IOException, FailingHttpStatusCodeException {
535         final WebWindow enclosingWindow = getEnclosingWindow();
536         final boolean isAboutBlank = getUrl() == UrlUtils.URL_ABOUT_BLANK;
537         if (isAboutBlank) {
538             // a frame contains first a faked "about:blank" before its real content specified by src gets loaded
539             if (enclosingWindow instanceof FrameWindow window
540                     && !window.getFrameElement().isContentLoaded()) {
541                 return;
542             }
543 
544             // save the URL that should be used to resolve relative URLs in this page
545             if (enclosingWindow instanceof TopLevelWindow topWindow) {
546                 final WebWindow openerWindow = topWindow.getOpener();
547                 if (openerWindow != null && openerWindow.getEnclosedPage() != null) {
548                     baseUrl_ = openerWindow.getEnclosedPage().getWebResponse().getWebRequest().getUrl();
549                 }
550             }
551         }
552 
553         if (!isAboutBlank) {
554             setReadyState(READY_STATE_INTERACTIVE);
555             getDocumentElement().setReadyState(READY_STATE_INTERACTIVE);
556             executeEventHandlersIfNeeded(Event.TYPE_READY_STATE_CHANGE);
557         }
558 
559         executeDeferredScriptsIfNeeded();
560 
561         executeEventHandlersIfNeeded(Event.TYPE_DOM_DOCUMENT_LOADED);
562 
563         // postponed actions are more or less the async scripts,
564         // they are running in real browsers whenever the download is done
565         processPostponedActionsIfNeeded();
566 
567         loadFrames();
568 
569         // don't set the ready state if we really load the blank page into the window
570         // see Node.initInlineFrameIfNeeded()
571         if (!isAboutBlank) {
572             setReadyState(READY_STATE_COMPLETE);
573             getDocumentElement().setReadyState(READY_STATE_COMPLETE);
574             executeEventHandlersIfNeeded(Event.TYPE_READY_STATE_CHANGE);
575         }
576 
577         // frame initialization has a different order
578         boolean isFrameWindow = enclosingWindow instanceof FrameWindow;
579         boolean isFirstPageInFrameWindow = false;
580         if (isFrameWindow) {
581             isFrameWindow = ((FrameWindow) enclosingWindow).getFrameElement() instanceof HtmlFrame;
582 
583             final History hist = enclosingWindow.getHistory();
584             if (hist.getLength() > 0 && UrlUtils.URL_ABOUT_BLANK == hist.getUrl(0)) {
585                 isFirstPageInFrameWindow = hist.getLength() <= 2;
586             }
587             else {
588                 isFirstPageInFrameWindow = enclosingWindow.getHistory().getLength() < 2;
589             }
590         }
591 
592         if (isFrameWindow && !isFirstPageInFrameWindow) {
593             executeEventHandlersIfNeeded(Event.TYPE_LOAD);
594         }
595 
596         for (final BaseFrameElement frameElement : new ArrayList<>(frameElements_)) {
597             if (frameElement instanceof HtmlFrame) {
598                 final Page page = frameElement.getEnclosedWindow().getEnclosedPage();
599                 if (page != null && page.isHtmlPage()) {
600                     ((HtmlPage) page).executeEventHandlersIfNeeded(Event.TYPE_LOAD);
601                 }
602             }
603         }
604 
605         if (!isFrameWindow) {
606             executeEventHandlersIfNeeded(Event.TYPE_LOAD);
607 
608             if (!isAboutBlank && enclosingWindow.getWebClient().isJavaScriptEnabled()
609                     && hasFeature(EVENT_FOCUS_ON_LOAD)) {
610                 final HtmlElement body = getBody();
611                 if (body != null) {
612                     final Event event = new Event((Window) enclosingWindow.getScriptableObject(), Event.TYPE_FOCUS);
613                     body.fireEvent(event);
614                 }
615             }
616         }
617 
618         // like in the browsers the autofocus is processed after the load event
619         autofocusAfterLoad_ = true;
620         processAutofocusCandidates();
621 
622         try {
623             while (!afterLoadActions_.isEmpty()) {
624                 final PostponedAction action = afterLoadActions_.remove(0);
625                 action.execute();
626             }
627         }
628         catch (final IOException e) {
629             throw e;
630         }
631         catch (final Exception e) {
632             throw new RuntimeException(e);
633         }
634         executeRefreshIfNeeded();
635     }
636 
637     /**
638      * Adds an action that should be executed once the page has been loaded.
639      * @param action the action
640      */
641     void addAfterLoadAction(final PostponedAction action) {
642         afterLoadActions_.add(action);
643     }
644 
645     /**
646      * Clean up this page.
647      */
648     @Override
649     public void cleanUp() {
650         //To avoid endless recursion caused by window.close() in onUnload
651         if (cleaning_) {
652             return;
653         }
654 
655         cleaning_ = true;
656         try {
657             super.cleanUp();
658             executeEventHandlersIfNeeded(Event.TYPE_UNLOAD);
659             deregisterFramesIfNeeded();
660         }
661         finally {
662             cleaning_ = false;
663 
664             if (autoCloseableList_ != null) {
665                 for (final AutoCloseable closeable : new ArrayList<>(autoCloseableList_)) {
666                     try {
667                         closeable.close();
668                     }
669                     catch (final Exception e) {
670                         LOG.error("Closing the autoclosable " + closeable + " failed", e);
671                     }
672                 }
673             }
674         }
675     }
676 
677     /**
678      * {@inheritDoc}
679      */
680     @Override
681     public HtmlElement getDocumentElement() {
682         return (HtmlElement) super.getDocumentElement();
683     }
684 
685     /**
686      * Returns the document's {@code body} element.
687      *
688      * @return the document's {@code body} element, or {@code null} if it does
689      *         not exist
690      */
691     public HtmlBody getBody() {
692         final DomElement doc = getDocumentElement();
693         if (doc != null) {
694             for (final DomNode node : doc.getChildren()) {
695                 if (node instanceof HtmlBody body) {
696                     return body;
697                 }
698             }
699         }
700         return null;
701     }
702 
703     /**
704      * Returns the head element.
705      * @return the head element
706      */
707     public HtmlElement getHead() {
708         final DomElement doc = getDocumentElement();
709         if (doc != null) {
710             for (final DomNode node : doc.getChildren()) {
711                 if (node instanceof HtmlHead) {
712                     return (HtmlElement) node;
713                 }
714             }
715         }
716         return null;
717     }
718 
719     /**
720      * {@inheritDoc}
721      */
722     @Override
723     public Document getOwnerDocument() {
724         return null;
725     }
726 
727     /**
728      * {@inheritDoc}
729      * Not yet implemented.
730      */
731     @Override
732     public org.w3c.dom.Node importNode(final org.w3c.dom.Node importedNode, final boolean deep) {
733         throw new UnsupportedOperationException("HtmlPage.importNode is not yet implemented.");
734     }
735 
736     /**
737      * {@inheritDoc}
738      * Not yet implemented.
739      */
740     @Override
741     public String getInputEncoding() {
742         throw new UnsupportedOperationException("HtmlPage.getInputEncoding is not yet implemented.");
743     }
744 
745     /**
746      * {@inheritDoc}
747      */
748     @Override
749     public String getXmlEncoding() {
750         return null;
751     }
752 
753     /**
754      * {@inheritDoc}
755      */
756     @Override
757     public boolean getXmlStandalone() {
758         return false;
759     }
760 
761     /**
762      * {@inheritDoc}
763      * Not yet implemented.
764      */
765     @Override
766     public void setXmlStandalone(final boolean xmlStandalone) throws DOMException {
767         throw new UnsupportedOperationException("HtmlPage.setXmlStandalone is not yet implemented.");
768     }
769 
770     /**
771      * {@inheritDoc}
772      */
773     @Override
774     public String getXmlVersion() {
775         return null;
776     }
777 
778     /**
779      * {@inheritDoc}
780      * Not yet implemented.
781      */
782     @Override
783     public void setXmlVersion(final String xmlVersion) throws DOMException {
784         throw new UnsupportedOperationException("HtmlPage.setXmlVersion is not yet implemented.");
785     }
786 
787     /**
788      * {@inheritDoc}
789      * Not yet implemented.
790      */
791     @Override
792     public boolean getStrictErrorChecking() {
793         throw new UnsupportedOperationException("HtmlPage.getStrictErrorChecking is not yet implemented.");
794     }
795 
796     /**
797      * {@inheritDoc}
798      * Not yet implemented.
799      */
800     @Override
801     public void setStrictErrorChecking(final boolean strictErrorChecking) {
802         throw new UnsupportedOperationException("HtmlPage.setStrictErrorChecking is not yet implemented.");
803     }
804 
805     /**
806      * {@inheritDoc}
807      * Not yet implemented.
808      */
809     @Override
810     public String getDocumentURI() {
811         throw new UnsupportedOperationException("HtmlPage.getDocumentURI is not yet implemented.");
812     }
813 
814     /**
815      * {@inheritDoc}
816      * Not yet implemented.
817      */
818     @Override
819     public void setDocumentURI(final String documentURI) {
820         throw new UnsupportedOperationException("HtmlPage.setDocumentURI is not yet implemented.");
821     }
822 
823     /**
824      * {@inheritDoc}
825      * Not yet implemented.
826      */
827     @Override
828     public org.w3c.dom.Node adoptNode(final org.w3c.dom.Node source) throws DOMException {
829         throw new UnsupportedOperationException("HtmlPage.adoptNode is not yet implemented.");
830     }
831 
832     /**
833      * {@inheritDoc}
834      * Not yet implemented.
835      */
836     @Override
837     public DOMConfiguration getDomConfig() {
838         throw new UnsupportedOperationException("HtmlPage.getDomConfig is not yet implemented.");
839     }
840 
841     /**
842      * {@inheritDoc}
843      * Not yet implemented.
844      */
845     @Override
846     public org.w3c.dom.Node renameNode(final org.w3c.dom.Node newNode, final String namespaceURI,
847         final String qualifiedName) throws DOMException {
848         throw new UnsupportedOperationException("HtmlPage.renameNode is not yet implemented.");
849     }
850 
851     /**
852      * {@inheritDoc}
853      */
854     @Override
855     public Charset getCharset() {
856         if (originalCharset_ == null) {
857             originalCharset_ = getWebResponse().getContentCharset();
858         }
859         return originalCharset_;
860     }
861 
862     /**
863      * {@inheritDoc}
864      */
865     @Override
866     public String getContentType() {
867         return getWebResponse().getContentType();
868     }
869 
870     /**
871      * {@inheritDoc}
872      * Not yet implemented.
873      */
874     @Override
875     public DOMImplementation getImplementation() {
876         throw new UnsupportedOperationException("HtmlPage.getImplementation is not yet implemented.");
877     }
878 
879     /**
880      * {@inheritDoc}
881      * @param tagName the tag name, preferably in lowercase
882      */
883     @Override
884     public DomElement createElement(final String tagName) {
885         final String name = tagName.indexOf(':') == -1
886                                 ? org.htmlunit.util.StringUtils.toRootLowerCase(tagName)
887                                 : tagName;
888         return getWebClient().getPageCreator().getHtmlParser().getFactory(name)
889                     .createElementNS(this, null, name, null);
890     }
891 
892     /**
893      * {@inheritDoc}
894      */
895     @Override
896     public DomElement createElementNS(final String namespaceURI, final String qualifiedName) {
897         return getWebClient().getPageCreator().getHtmlParser()
898                 .getElementFactory(this, namespaceURI, qualifiedName, false, true)
899                 .createElementNS(this, namespaceURI, qualifiedName, null);
900     }
901 
902     /**
903      * {@inheritDoc}
904      * <p>Unlike {@link #createAttribute(String)} the name is not lower cased.</p>
905      */
906     @Override
907     public DomAttr createAttributeNS(final String namespaceURI, final String qualifiedName) {
908         // an empty namespace is the same as no namespace
909         final String namespace = org.htmlunit.util.StringUtils.isEmptyOrNull(namespaceURI) ? null : namespaceURI;
910 
911         final int colonPosition = qualifiedName.indexOf(':');
912         final String prefix = colonPosition == -1 ? null : qualifiedName.substring(0, colonPosition);
913         final boolean xmlns = XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)
914                 || XMLConstants.XMLNS_ATTRIBUTE.equals(qualifiedName);
915 
916         if ((prefix != null && namespace == null)
917                 || (XMLConstants.XML_NS_PREFIX.equals(prefix) && !XMLConstants.XML_NS_URI.equals(namespace))
918                 || (xmlns && !XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace))
919                 || (!xmlns && XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace))) {
920             throw new DOMException(DOMException.NAMESPACE_ERR,
921                     "createAttributeNS: invalid namespace '" + namespaceURI + "' for '" + qualifiedName + "'");
922         }
923 
924         return new DomAttr(this, namespace, qualifiedName, "", false);
925     }
926 
927     /**
928      * {@inheritDoc}
929      * <p>Entity references are not supported by HTML documents (DOM Level 2 Core). They are removed
930      * from the DOM standard and the browsers do not offer {@code createEntityReference}.
931      * </p>
932      */
933     @Override
934     public EntityReference createEntityReference(final String name) {
935         throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
936                 "HtmlPage.createEntityReference: entity references are not supported by HTML documents.");
937     }
938 
939     /**
940      * {@inheritDoc}
941      * <p>DOM Level 2 Core forbids processing instructions in HTML documents, but the DOM standard and the
942      * browsers allow them and {@code document.createProcessingInstruction()} relies on this.
943      * </p>
944      */
945     @Override
946     public DomProcessingInstruction createProcessingInstruction(final String target, final String data) {
947         return new DomProcessingInstruction(this, target, data);
948     }
949 
950     /**
951      * {@inheritDoc}
952      */
953     @Override
954     public DomElement getElementById(final String elementId) {
955         if (elementId != null) {
956             ensureMappedElementsBuilt();
957             final MappedElementIndexEntry elements = idMap_.get(elementId);
958             if (elements != null) {
959                 return elements.first();
960             }
961         }
962         return null;
963     }
964 
965     /**
966      * Returns the {@link HtmlAnchor} with the specified name.
967      *
968      * @param name the name to search by
969      * @return the {@link HtmlAnchor} with the specified name
970      * @throws ElementNotFoundException if the anchor could not be found
971      */
972     public HtmlAnchor getAnchorByName(final String name) throws ElementNotFoundException {
973         return getDocumentElement().getOneHtmlElementByAttribute("a", DomElement.NAME_ATTRIBUTE, name);
974     }
975 
976     /**
977      * Returns the {@link HtmlAnchor} with the specified href.
978      *
979      * @param href the string to search by
980      * @return the HtmlAnchor
981      * @throws ElementNotFoundException if the anchor could not be found
982      */
983     public HtmlAnchor getAnchorByHref(final String href) throws ElementNotFoundException {
984         return getDocumentElement().getOneHtmlElementByAttribute("a", "href", href);
985     }
986 
987     /**
988      * Returns a list of all anchors contained in this page.
989      * @return the list of {@link HtmlAnchor} in this page
990      */
991     public List<HtmlAnchor> getAnchors() {
992         return getDocumentElement().getElementsByTagNameImpl("a");
993     }
994 
995     /**
996      * Returns the first anchor with the specified text.
997      * @param text the text to search for
998      * @return the first anchor that was found
999      * @throws ElementNotFoundException if no anchors are found with the specified text
1000      */
1001     public HtmlAnchor getAnchorByText(final String text) throws ElementNotFoundException {
1002         WebAssert.notNull("text", text);
1003 
1004         for (final HtmlAnchor anchor : getAnchors()) {
1005             if (text.equals(anchor.asNormalizedText())) {
1006                 return anchor;
1007             }
1008         }
1009         throw new ElementNotFoundException("a", "<text>", text);
1010     }
1011 
1012     /**
1013      * Returns the first form that matches the specified name.
1014      * @param name the name to search for
1015      * @return the first form
1016      * @throws ElementNotFoundException If no forms match the specified result.
1017      */
1018     public HtmlForm getFormByName(final String name) throws ElementNotFoundException {
1019         final List<HtmlForm> forms = getDocumentElement()
1020                 .getElementsByAttribute("form", DomElement.NAME_ATTRIBUTE, name);
1021         if (forms.isEmpty()) {
1022             throw new ElementNotFoundException("form", DomElement.NAME_ATTRIBUTE, name);
1023         }
1024         return forms.get(0);
1025     }
1026 
1027     /**
1028      * Returns a list of all the forms in this page.
1029      * @return all the forms in this page
1030      */
1031     public List<HtmlForm> getForms() {
1032         return getDocumentElement().getElementsByTagNameImpl("form");
1033     }
1034 
1035     /**
1036      * Given a relative URL (ie <code>/foo</code>), returns a fully-qualified URL based on
1037      * the URL that was used to load this page.
1038      *
1039      * @param relativeUrl the relative URL
1040      * @return the fully-qualified URL for the specified relative URL
1041      * @throws MalformedURLException if an error occurred when creating a URL object
1042      */
1043     public URL getFullyQualifiedUrl(final String relativeUrl) throws MalformedURLException {
1044         // to handle http: and http:/ in FF (Bug #474)
1045         String url = relativeUrl;
1046         boolean incorrectnessNotified = false;
1047         while (url.startsWith("http:") && !url.startsWith("http://")) {
1048             if (!incorrectnessNotified) {
1049                 notifyIncorrectness("Incorrect URL \"" + url + "\" has been corrected");
1050                 incorrectnessNotified = true;
1051             }
1052             url = "http:/" + url.substring(5);
1053         }
1054 
1055         return WebClient.expandUrl(getBaseURL(), url);
1056     }
1057 
1058     /**
1059      * Given a target attribute value, resolve the target using a base target for the page.
1060      *
1061      * @param elementTarget the target specified as an attribute of the element
1062      * @return the resolved target to use for the element
1063      */
1064     public String getResolvedTarget(final String elementTarget) {
1065         final String resolvedTarget;
1066         if (base_ == null) {
1067             resolvedTarget = elementTarget;
1068         }
1069         else if (elementTarget != null && !elementTarget.isEmpty()) {
1070             resolvedTarget = elementTarget;
1071         }
1072         else {
1073             resolvedTarget = base_.getTargetAttribute();
1074         }
1075         return resolvedTarget;
1076     }
1077 
1078     /**
1079      * Returns a list of ids (strings) that correspond to the tabbable elements
1080      * in this page. Return them in the same order specified in {@link #getTabbableElements}
1081      *
1082      * @return the list of id's
1083      */
1084     public List<String> getTabbableElementIds() {
1085         final List<String> list = new ArrayList<>();
1086 
1087         for (final HtmlElement element : getTabbableElements()) {
1088             list.add(element.getId());
1089         }
1090 
1091         return Collections.unmodifiableList(list);
1092     }
1093 
1094     /**
1095      * Returns a list of all elements that are tabbable in the order that will
1096      * be used for tabbing.
1097      * <p>
1098      * The rules for determining tab order are as follows:
1099      * </p>
1100      * <ol>
1101      *   <li>Those elements that support the tabindex attribute and assign a
1102      *   positive value to it are navigated first. Navigation proceeds from the
1103      *   element with the lowest tabindex value to the element with the highest
1104      *   value. Values need not be sequential nor must they begin with any
1105      *   particular value. Elements that have identical tabindex values should
1106      *   be navigated in the order they appear in the character stream.</li>
1107      *   <li>Those elements that do not support the tabindex attribute or
1108      *   support it and assign it a value of "0" are navigated next. These
1109      *   elements are navigated in the order they appear in the character
1110      *   stream.</li>
1111      *   <li>Elements that are disabled do not participate in the tabbing
1112      *   order.</li>
1113      *   <li>Hidden inputs do not participate in the tabbing order.</li>
1114      * </ol>
1115      * <p>
1116      * Additionally, the value of tabindex must be within 0 and 32767. Any
1117      * values outside this range will be ignored.
1118      * </p>
1119      * <p>
1120      * The following elements support the <code>tabindex</code> attribute:
1121      * A, AREA, BUTTON, INPUT, OBJECT, SELECT, and TEXTAREA.
1122      * </p>
1123      *
1124      * @return all the tabbable elements in proper tab order
1125      */
1126     public List<HtmlElement> getTabbableElements() {
1127         final List<HtmlElement> tabbableElements = new ArrayList<>();
1128         for (final HtmlElement element : getHtmlElementDescendants()) {
1129             final String tagName = element.getTagName();
1130             // hidden inputs are never tabbable
1131             if (TABBABLE_TAGS.contains(tagName) && !(element instanceof HtmlHiddenInput)) {
1132                 final boolean disabled = element.isDisabledElementAndDisabled();
1133                 if (!disabled && !HtmlElement.TAB_INDEX_OUT_OF_BOUNDS.equals(element.getTabIndex())) {
1134                     tabbableElements.add(element);
1135                 }
1136             }
1137         }
1138         tabbableElements.sort(createTabOrderComparator());
1139         return Collections.unmodifiableList(tabbableElements);
1140     }
1141 
1142     private static Comparator<HtmlElement> createTabOrderComparator() {
1143         return (element1, element2) -> {
1144             final Short i1 = element1.getTabIndex();
1145             final Short i2 = element2.getTabIndex();
1146 
1147             final short index1;
1148             if (i1 == null) {
1149                 index1 = -1;
1150             }
1151             else {
1152                 index1 = i1.shortValue();
1153             }
1154 
1155             final short index2;
1156             if (i2 == null) {
1157                 index2 = -1;
1158             }
1159             else {
1160                 index2 = i2.shortValue();
1161             }
1162 
1163             final int result;
1164             if (index1 > 0 && index2 > 0) {
1165                 result = index1 - index2;
1166             }
1167             else if (index1 > 0) {
1168                 result = -1;
1169             }
1170             else if (index2 > 0) {
1171                 result = 1;
1172             }
1173             else if (index1 == index2) {
1174                 result = 0;
1175             }
1176             else {
1177                 result = index2 - index1;
1178             }
1179 
1180             return result;
1181         };
1182     }
1183 
1184     /**
1185      * Returns the HTML element that is assigned to the specified access key. An
1186      * access key (aka mnemonic key) is used for keyboard navigation of the
1187      * page.
1188      * <p>
1189      * Only the following HTML elements may have <code>accesskey</code>s defined: A, AREA,
1190      * BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA.
1191      * </p>
1192      *
1193      * @param accessKey the key to look for
1194      * @return the HTML element that is assigned to the specified key or null
1195      *      if no elements can be found that match the specified key.
1196      */
1197     public HtmlElement getHtmlElementByAccessKey(final char accessKey) {
1198         final List<HtmlElement> elements = getHtmlElementsByAccessKey(accessKey);
1199         if (elements.isEmpty()) {
1200             return null;
1201         }
1202         return elements.get(0);
1203     }
1204 
1205     /**
1206      * Returns all the HTML elements that are assigned to the specified access key. An
1207      * access key (aka mnemonic key) is used for keyboard navigation of the
1208      * page.
1209      * <p>
1210      * The HTML specification seems to indicate that one accesskey cannot be used
1211      * for multiple elements however Internet Explorer does seem to support this.
1212      * It's worth noting that Firefox does not support multiple elements with one
1213      * access key so you are making your HTML browser specific if you rely on this
1214      * feature.
1215      * </p>
1216      *
1217      * <p>
1218      * Only the following HTML elements may have <code>accesskey</code>s defined: A, AREA,
1219      * BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA.
1220      * </p>
1221      *
1222      * @param accessKey the key to look for
1223      * @return the elements that are assigned to the specified accesskey
1224      */
1225     public List<HtmlElement> getHtmlElementsByAccessKey(final char accessKey) {
1226         final List<HtmlElement> elements = new ArrayList<>();
1227 
1228         final String searchString = Character.toString(accessKey).toLowerCase(Locale.ROOT);
1229         for (final HtmlElement element : getHtmlElementDescendants()) {
1230             if (ACCEPTABLE_TAG_NAMES.contains(element.getTagName())) {
1231                 final String accessKeyAttribute = element.getAttributeDirect("accesskey");
1232                 if (searchString.equalsIgnoreCase(accessKeyAttribute)) {
1233                     elements.add(element);
1234                 }
1235             }
1236         }
1237 
1238         return elements;
1239     }
1240 
1241     /**
1242      * <p>Executes the specified JavaScript code within the page. The usage would be similar to what can
1243      * be achieved to execute JavaScript in the current page by entering "javascript:...some JS code..."
1244      * in the URL field of a native browser.</p>
1245      * <p><b>Note:</b> the provided code won't be executed if JavaScript has been disabled on the WebClient
1246      * (see {@link org.htmlunit.WebClient#isJavaScriptEnabled()}).</p>
1247      * @param sourceCode the JavaScript code to execute
1248      * @return a ScriptResult which will contain both the current page (which may be different from
1249      *         the previous page) and a JavaScript result object
1250      */
1251     public ScriptResult executeJavaScript(final String sourceCode) {
1252         return executeJavaScript(sourceCode, "injected script", 1);
1253     }
1254 
1255     /**
1256      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1257      * <p>
1258      * Execute the specified JavaScript if a JavaScript engine was successfully
1259      * instantiated. If this JavaScript causes the current page to be reloaded
1260      * (through location="" or form.submit()) then return the new page, otherwise
1261      * return the current page.
1262      * </p>
1263      * <p><b>Please note:</b> Although this method is public, it is not intended for
1264      * general execution of JavaScript. Users of HtmlUnit should interact with the pages
1265      * as a user would by clicking on buttons or links and having the JavaScript event
1266      * handlers execute as needed.
1267      * </p>
1268      *
1269      * @param sourceCode the JavaScript code to execute
1270      * @param sourceName the name for this chunk of code (will be displayed in error messages)
1271      * @param startLine the line at which the script source starts
1272      * @return a ScriptResult which will contain both the current page (which may be different from
1273      *         the previous page) and a JavaScript result object.
1274      */
1275     public ScriptResult executeJavaScript(final String sourceCode, final String sourceName, final int startLine) {
1276         if (!getWebClient().isJavaScriptEnabled()) {
1277             return new ScriptResult(JavaScriptEngine.UNDEFINED);
1278         }
1279 
1280         String code = sourceCode;
1281         if (org.htmlunit.util.StringUtils.startsWithIgnoreCase(code,
1282                                                 JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
1283             code = code.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length()).trim();
1284             if (code.startsWith("return ")) {
1285                 code = code.substring("return ".length());
1286             }
1287         }
1288 
1289         final Window window = getEnclosingWindow().getScriptableObject();
1290         final VarScope scope = ScriptableObject.getTopLevelScope(window.getParentScope());
1291 
1292         final Object result = getWebClient().getJavaScriptEngine()
1293                 .execute(this, scope, code, sourceName, startLine);
1294         return new ScriptResult(result);
1295     }
1296 
1297     /** Various possible external JavaScript file loading results. */
1298     enum JavaScriptLoadResult {
1299         /** The load was aborted and nothing was done. */
1300         NOOP,
1301         /** The load was aborted and nothing was done. */
1302         NO_CONTENT,
1303         /** The external JavaScript file was downloaded and compiled successfully. */
1304         SUCCESS,
1305         /** The external JavaScript file was not downloaded successfully. */
1306         DOWNLOAD_ERROR,
1307         /** The external JavaScript file was downloaded but was not compiled successfully. */
1308         COMPILATION_ERROR
1309     }
1310 
1311     /**
1312      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1313      *
1314      * @param srcAttribute the source attribute from the script tag
1315      * @param scriptCharset the charset from the script tag
1316      * @param crossorigin the crossorigin attribute of the script tag is set
1317      * @param element the script element (used to check redirects against the Content-Security-Policy)
1318      *        or {@code null}
1319      * @return the result of loading the specified external JavaScript file
1320      * @throws FailingHttpStatusCodeException if the request's status code indicates a request
1321      *         failure and the {@link WebClient} was configured to throw exceptions on failing
1322      *         HTTP status codes
1323      */
1324     JavaScriptLoadResult loadExternalJavaScriptFile(final String srcAttribute,
1325                             final Charset scriptCharset, final boolean crossorigin, final DomElement element)
1326         throws FailingHttpStatusCodeException {
1327 
1328         final WebClient client = getWebClient();
1329         if (org.htmlunit.util.StringUtils.isBlank(srcAttribute) || !client.isJavaScriptEnabled()) {
1330             return JavaScriptLoadResult.NOOP;
1331         }
1332 
1333         final URL scriptURL;
1334         try {
1335             scriptURL = getFullyQualifiedUrl(srcAttribute);
1336             final String protocol = scriptURL.getProtocol();
1337             if ("javascript".equals(protocol)) {
1338                 if (LOG.isInfoEnabled()) {
1339                     LOG.info("Ignoring script src [" + srcAttribute + "]");
1340                 }
1341                 return JavaScriptLoadResult.NOOP;
1342             }
1343             if (!"http".equals(protocol) && !"https".equals(protocol)
1344                     && !"data".equals(protocol) && !"file".equals(protocol)) {
1345                 client.getJavaScriptErrorListener().malformedScriptURL(this, srcAttribute,
1346                         new MalformedURLException("unknown protocol: '" + protocol + "'"));
1347                 return JavaScriptLoadResult.NOOP;
1348             }
1349         }
1350         catch (final MalformedURLException e) {
1351             client.getJavaScriptErrorListener().malformedScriptURL(this, srcAttribute, e);
1352             return JavaScriptLoadResult.NOOP;
1353         }
1354 
1355         final Object script;
1356         try {
1357             script = loadJavaScriptFromUrl(scriptURL, scriptCharset, crossorigin, element);
1358         }
1359         catch (final IOException e) {
1360             client.getJavaScriptErrorListener().loadScriptError(this, scriptURL, e);
1361             return JavaScriptLoadResult.DOWNLOAD_ERROR;
1362         }
1363         catch (final FailingHttpStatusCodeException e) {
1364             if (e.getStatusCode() == HttpStatus.NO_CONTENT_204) {
1365                 return JavaScriptLoadResult.NO_CONTENT;
1366             }
1367             client.getJavaScriptErrorListener().loadScriptError(this, scriptURL, e);
1368             throw e;
1369         }
1370 
1371         if (script == null) {
1372             return JavaScriptLoadResult.COMPILATION_ERROR;
1373         }
1374 
1375         final Window window = getEnclosingWindow().getScriptableObject();
1376         final VarScope scope = ScriptableObject.getTopLevelScope(window.getParentScope());
1377 
1378         @SuppressWarnings("unchecked")
1379         final AbstractJavaScriptEngine<Object> engine = (AbstractJavaScriptEngine<Object>) client.getJavaScriptEngine();
1380         engine.execute(this, scope, script);
1381         return JavaScriptLoadResult.SUCCESS;
1382     }
1383 
1384     /**
1385      * Loads JavaScript from the specified URL. This method may return {@code null} if
1386      * there is a problem loading the code from the specified URL.
1387      *
1388      * @param url the URL of the script
1389      * @param scriptCharset the charset from the script tag
1390      * @param crossorigin the crossorigin attribute of the script tag is set
1391      * @param element the script element (used to check redirects against the Content-Security-Policy)
1392      *        or {@code null}
1393      * @return the content of the file, or {@code null} if we ran into a compile error
1394      * @throws IOException if there is a problem downloading the JavaScript file
1395      * @throws FailingHttpStatusCodeException if the request's status code indicates a request
1396      *         failure and the {@link WebClient} was configured to throw exceptions on failing
1397      *         HTTP status codes
1398      */
1399     private Object loadJavaScriptFromUrl(final URL url, final Charset scriptCharset,
1400                     final boolean crossorigin, final DomElement element) throws IOException,
1401         FailingHttpStatusCodeException {
1402 
1403         // like the browsers, a page not loaded from a file is not allowed to load a local file (network error)
1404         if (!isLocalResourceAccessAllowed(url)) {
1405             notifyIncorrectness("Not allowed to load local resource: " + url);
1406             throw new IOException("Not allowed to load local resource: " + url);
1407         }
1408 
1409         final WebRequest referringRequest = getWebResponse().getWebRequest();
1410 
1411         final WebClient client = getWebClient();
1412         final WebRequest request = new WebRequest(url);
1413         // copy all headers from the referring request
1414         request.setAdditionalHeaders(new HashMap<>(referringRequest.getAdditionalHeaders()));
1415         if (!UrlUtils.isSameOrigin(referringRequest.getUrl(), url)) {
1416             // credentials are not forwarded to another origin
1417             request.removeAdditionalHeader("Authorization");
1418         }
1419 
1420         // at least overwrite this headers
1421         request.setAdditionalHeader(HttpHeader.ACCEPT, client.getBrowserVersion().getScriptAcceptHeader());
1422 
1423         request.setFetchDestination(WebRequest.FetchDestination.SCRIPT);
1424         request.setRequestingUrl(referringRequest.getUrl());
1425         request.setSiteForCookies(getSiteForCookiesUrl());
1426         request.setFetchModeOverride(WebRequest.FetchMode.NO_CORS);
1427 
1428         request.setRefererHeader(referringRequest.getUrl());
1429         request.setReferrerPolicy(element == null ? getReferrerPolicy() : getReferrerPolicy(element));
1430         request.setCharset(scriptCharset);
1431 
1432         // use info from script tag or fall back to utf-8
1433         // https://www.rfc-editor.org/rfc/rfc9239#section-4.2
1434         if (scriptCharset != null) {
1435             request.setDefaultResponseContentCharset(scriptCharset);
1436         }
1437         else {
1438             request.setDefaultResponseContentCharset(StandardCharsets.UTF_8);
1439         }
1440 
1441         if (crossorigin) {
1442             request.setFetchModeOverride(WebRequest.FetchMode.CORS);
1443 
1444             // the Origin is the origin of this document (not the one of the script);
1445             // it is sent for cross-origin requests, Chrome sends it always
1446             final boolean crossOriginRequest = !UrlUtils.isSameOrigin(getOriginUrl(), url);
1447             if (crossOriginRequest || client.getBrowserVersion().hasFeature(HTTP_HEADER_CH_UA)) {
1448                 request.setAdditionalHeader(HttpHeader.ORIGIN, isOpaqueOrigin()
1449                         ? "null" : UrlUtils.getUrlWithProtocolAndAuthority(getOriginUrl()).toExternalForm());
1450             }
1451         }
1452 
1453         if (element != null && getContentSecurityPolicy() != null) {
1454             // like the browsers, redirects are checked (and upgraded) also
1455             ContentSecurityPolicy.upgradeInsecureRedirects(this, request);
1456             request.setRedirectFilter(
1457                 redirectUrl -> ContentSecurityPolicy.allowsExternalScript(this, element, redirectUrl, url));
1458         }
1459 
1460         // our cache is a bit strange;
1461         // loadWebResponse check the cache for the web response
1462         // AND also fixes the request url for the following cache lookups
1463         final WebResponse response = client.loadWebResponse(request);
1464         if (response == null) {
1465             throw new IOException("Redirect of the script '" + url
1466                     + "' blocked by the Content-Security-Policy.");
1467         }
1468 
1469         // now we can look into the cache with the fixed request for
1470         // a cached script
1471         final Cache cache = client.getCache();
1472         final Object cachedScript = cache.getCachedObject(request);
1473         if (cachedScript instanceof Script) {
1474             return cachedScript;
1475         }
1476 
1477         client.printContentIfNecessary(response);
1478         client.throwFailingHttpStatusCodeExceptionIfNecessary(response);
1479 
1480         final int statusCode = response.getStatusCode();
1481         if (statusCode == HttpStatus.NO_CONTENT_204) {
1482             throw new FailingHttpStatusCodeException(response);
1483         }
1484 
1485         if (!response.isSuccess()) {
1486             throw new IOException("Unable to download JavaScript from '" + url + "' (status " + statusCode + ").");
1487         }
1488 
1489         final String contentType = response.getContentType();
1490         if (contentType != null) {
1491             if (MimeType.isObsoleteJavascriptMimeType(contentType)) {
1492                 getWebClient().getIncorrectnessListener().notify(
1493                         "Obsolete content type encountered: '" + contentType + "' "
1494                                 + "for remotely loaded JavaScript element at '" + url + "'.", this);
1495             }
1496             else if (!MimeType.isJavascriptMimeType(contentType)) {
1497                 getWebClient().getIncorrectnessListener().notify(
1498                         "Expect content type of '" + MimeType.TEXT_JAVASCRIPT + "' "
1499                                 + "for remotely loaded JavaScript element at '" + url + "', "
1500                                 + "but got '" + contentType + "'.", this);
1501             }
1502         }
1503 
1504         final Charset scriptEncoding = response.getContentCharset();
1505         final String scriptCode = response.getContentAsString(scriptEncoding);
1506         if (null != scriptCode) {
1507             final AbstractJavaScriptEngine<?> javaScriptEngine = client.getJavaScriptEngine();
1508 
1509             final Window window = getEnclosingWindow().getScriptableObject();
1510             final VarScope scope = ScriptableObject.getTopLevelScope(window.getParentScope());
1511 
1512             final Object script = javaScriptEngine.compile(this, scope, scriptCode, url.toExternalForm(), 1);
1513             if (script != null && cache.cacheIfPossible(request, response, script)) {
1514                 // no cleanup if the response is stored inside the cache
1515                 return script;
1516             }
1517 
1518             response.cleanUp();
1519             return script;
1520         }
1521 
1522         response.cleanUp();
1523         return null;
1524     }
1525 
1526     /**
1527      * Returns the title like {@code document.title} does: the text of the first title element
1528      * with ASCII whitespace stripped and collapsed. Other spaces, including the non-breaking space, are kept.
1529      *
1530      * @return the title like {@code document.title}
1531      */
1532     public String getDocumentTitle() {
1533         final HtmlTitle title = getTitleElement();
1534         if (title == null) {
1535             return "";
1536         }
1537 
1538         final String titleTextContent = title.getText();
1539         final StringBuilder sb = new StringBuilder(titleTextContent.length());
1540         boolean pendingSpace = false;
1541         for (int i = 0; i < titleTextContent.length(); i++) {
1542             final char c = titleTextContent.charAt(i);
1543             if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r') {
1544                 pendingSpace = sb.length() > 0;
1545             }
1546             else {
1547                 if (pendingSpace) {
1548                     sb.append(' ');
1549                     pendingSpace = false;
1550                 }
1551                 sb.append(c);
1552             }
1553         }
1554         return sb.toString();
1555     }
1556 
1557     /**
1558      * Returns the normalized title of this page, or an empty string if no title element is present.
1559      * <p>
1560      * The returned text is normalized by collapsing consecutive whitespace characters
1561      * (including newlines and tabs) into a single space and trimming leading and trailing whitespace.
1562      * </p>
1563      *
1564      * @return the normalized page title, or an empty string if the title was not specified
1565      */
1566     public String getTitleText() {
1567         final HtmlTitle titleElement = getTitleElement();
1568         if (titleElement != null) {
1569             return titleElement.asNormalizedText();
1570         }
1571         return "";
1572     }
1573 
1574     /**
1575      * Sets the text for the title of this page. If there is not a title element
1576      * on this page, then one has to be generated.
1577      * @param message the new text
1578      */
1579     public void setTitleText(final String message) {
1580         HtmlTitle titleElement = getTitleElement();
1581         if (titleElement == null) {
1582             LOG.debug("No title element, creating one");
1583             final HtmlHead head = (HtmlHead) getFirstChildElement(getDocumentElement(), HtmlHead.class);
1584             if (head == null) {
1585                 // perhaps should we create head too?
1586                 throw new IllegalStateException("Headelement was not defined for this page");
1587             }
1588             final Map<String, DomAttr> emptyMap = Collections.emptyMap();
1589             titleElement = new HtmlTitle(HtmlTitle.TAG_NAME, this, emptyMap);
1590             if (head.getFirstChild() != null) {
1591                 head.getFirstChild().insertBefore(titleElement);
1592             }
1593             else {
1594                 head.appendChild(titleElement);
1595             }
1596         }
1597 
1598         titleElement.setText(message);
1599     }
1600 
1601     /**
1602      * Gets the first child of startElement that is an instance of the given class.
1603      * @param startElement the parent element
1604      * @param clazz the class to search for
1605      * @return {@code null} if no child found
1606      */
1607     private static DomElement getFirstChildElement(final DomElement startElement, final Class<?> clazz) {
1608         if (startElement == null) {
1609             return null;
1610         }
1611         for (final DomElement element : startElement.getChildElements()) {
1612             if (clazz.isInstance(element)) {
1613                 return element;
1614             }
1615         }
1616 
1617         return null;
1618     }
1619 
1620     /**
1621      * Gets the first child of startElement or it's children that is an instance of the given class.
1622      * @param startElement the parent element
1623      * @param clazz the class to search for
1624      * @return {@code null} if no child found
1625      */
1626     private DomElement getFirstChildElementRecursive(final DomElement startElement, final Class<?> clazz) {
1627         if (startElement == null) {
1628             return null;
1629         }
1630         for (final DomElement element : startElement.getChildElements()) {
1631             if (clazz.isInstance(element)) {
1632                 return element;
1633             }
1634             final DomElement childFound = getFirstChildElementRecursive(element, clazz);
1635             if (childFound != null) {
1636                 return childFound;
1637             }
1638         }
1639 
1640         return null;
1641     }
1642 
1643     /**
1644      * Gets the title element for this page. Returns null if one is not found.
1645      *
1646      * @return the title element for this page or null if this is not one
1647      */
1648     private HtmlTitle getTitleElement() {
1649         return (HtmlTitle) getFirstChildElementRecursive(getDocumentElement(), HtmlTitle.class);
1650     }
1651 
1652     /**
1653      * Looks for and executes any appropriate event handlers. Looks for body and frame tags.
1654      * @param eventType either {@link Event#TYPE_LOAD}, {@link Event#TYPE_UNLOAD}, or {@link Event#TYPE_BEFORE_UNLOAD}
1655      * @return {@code true} if user accepted <code>onbeforeunload</code> (not relevant to other events)
1656      */
1657     private boolean executeEventHandlersIfNeeded(final String eventType) {
1658         // If JavaScript isn't enabled, there's nothing for us to do.
1659         if (!getWebClient().isJavaScriptEnabled()) {
1660             return true;
1661         }
1662 
1663         // Execute the specified event on the document element.
1664         final WebWindow window = getEnclosingWindow();
1665         if (window.getScriptableObject() instanceof Window) {
1666             final Event event;
1667             if (Event.TYPE_BEFORE_UNLOAD.equals(eventType)) {
1668                 event = new BeforeUnloadEvent(this, eventType);
1669             }
1670             else {
1671                 event = new Event(this, eventType);
1672             }
1673 
1674             // This is the same as DomElement.fireEvent() and was copied
1675             // here so it could be used with HtmlPage.
1676             if (LOG.isDebugEnabled()) {
1677                 LOG.debug("Firing " + event);
1678             }
1679 
1680             final EventTarget jsNode;
1681             if (Event.TYPE_DOM_DOCUMENT_LOADED.equals(eventType)) {
1682                 jsNode = getScriptableObject();
1683             }
1684             else if (Event.TYPE_READY_STATE_CHANGE.equals(eventType)) {
1685                 jsNode = getDocumentElement().getScriptableObject();
1686             }
1687             else {
1688                 // The load/beforeunload/unload events target Document but paths Window only (tested in Chrome/FF)
1689                 jsNode = window.getScriptableObject();
1690             }
1691 
1692             ((JavaScriptEngine) getWebClient().getJavaScriptEngine()).callSecured(cx -> jsNode.fireEvent(event), this);
1693 
1694             if (!isOnbeforeunloadAccepted(this, event)) {
1695                 return false;
1696             }
1697         }
1698 
1699         // If this page was loaded in a frame, execute the version of the event specified on the frame tag.
1700         if (window instanceof FrameWindow fw) {
1701             final BaseFrameElement frame = fw.getFrameElement();
1702 
1703             // if part of a document fragment, then the load event is not triggered
1704             if (Event.TYPE_LOAD.equals(eventType) && frame.getParentNode() instanceof DomDocumentFragment) {
1705                 return true;
1706             }
1707 
1708             if (frame.hasEventHandlers("on" + eventType)) {
1709                 if (LOG.isDebugEnabled()) {
1710                     LOG.debug("Executing on" + eventType + " handler for " + frame);
1711                 }
1712                 if (window.getScriptableObject() instanceof Window) {
1713                     final Event event;
1714                     if (Event.TYPE_BEFORE_UNLOAD.equals(eventType)) {
1715                         event = new BeforeUnloadEvent(frame, eventType);
1716                     }
1717                     else {
1718                         event = new Event(frame, eventType);
1719                     }
1720                     // This fires the "load" event for the <frame> element which, like all non-window
1721                     // load events, propagates up to Document but not Window.  The "load" event for
1722                     // <frameset> on the other hand, like that of <body>, is handled above where it is
1723                     // fired against Document and directed to Window.
1724                     frame.fireEvent(event);
1725 
1726                     if (!isOnbeforeunloadAccepted((HtmlPage) frame.getPage(), event)) {
1727                         return false;
1728                     }
1729                 }
1730             }
1731         }
1732 
1733         return true;
1734     }
1735 
1736     /**
1737      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1738      *
1739      * @return true if the OnbeforeunloadHandler has accepted to change the page
1740      */
1741     public boolean isOnbeforeunloadAccepted() {
1742         return executeEventHandlersIfNeeded(Event.TYPE_BEFORE_UNLOAD);
1743     }
1744 
1745     private boolean isOnbeforeunloadAccepted(final HtmlPage page, final Event event) {
1746         if (event instanceof BeforeUnloadEvent beforeUnloadEvent) {
1747             if (beforeUnloadEvent.isBeforeUnloadMessageSet()) {
1748                 final OnbeforeunloadHandler handler = getWebClient().getOnbeforeunloadHandler();
1749                 if (handler == null) {
1750                     LOG.warn("document.onbeforeunload() returned a string in event.returnValue,"
1751                             + " but no onbeforeunload handler installed.");
1752                 }
1753                 else {
1754                     final String message = JavaScriptEngine.toString(beforeUnloadEvent.getReturnValue());
1755                     return handler.handleEvent(page, message);
1756                 }
1757             }
1758         }
1759         return true;
1760     }
1761 
1762     /**
1763      * If a refresh has been specified either through a meta tag or an HTTP
1764      * response header, then perform that refresh.
1765      * @throws IOException if an IO problem occurs
1766      */
1767     private void executeRefreshIfNeeded() throws IOException {
1768         // If this page is not in a frame then a refresh has already happened,
1769         // most likely through the JavaScript onload handler, so we don't do a
1770         // second refresh.
1771         final WebWindow window = getEnclosingWindow();
1772         if (window == null) {
1773             return;
1774         }
1775 
1776         final String refreshString = getRefreshStringOrNull();
1777         if (refreshString == null || refreshString.isEmpty()) {
1778             return;
1779         }
1780 
1781         final double time;
1782         final URL url;
1783 
1784         final int index = StringUtils.indexOfAnyBut(refreshString, "0123456789.");
1785 
1786         if (index == -1) {
1787             // Format: <meta http-equiv='refresh' content='10'>
1788             try {
1789                 time = Double.parseDouble(refreshString);
1790             }
1791             catch (final NumberFormatException e) {
1792                 if (LOG.isErrorEnabled()) {
1793                     LOG.error("Malformed refresh string (no ';' but not a number): " + refreshString, e);
1794                 }
1795                 return;
1796             }
1797             url = getUrl();
1798         }
1799         else {
1800             // Format: <meta http-equiv='refresh' content='10;url=http://www.blah.com'>
1801             try {
1802                 time = Double.parseDouble(refreshString.substring(0, index));
1803             }
1804             catch (final NumberFormatException e) {
1805                 if (LOG.isErrorEnabled()) {
1806                     LOG.error("Malformed refresh string (no valid number before ';') " + refreshString, e);
1807                 }
1808                 return;
1809             }
1810 
1811             String urlPart = refreshString.substring(index);
1812             final char separator = urlPart.charAt(0);
1813             if (";, \r\n\t".indexOf(separator) >= 0) {
1814                 urlPart = StringUtils.stripStart(urlPart, ";, \r\n\t");
1815                 urlPart = urlPart.toLowerCase(Locale.ROOT);
1816                 if (urlPart.startsWith("url")) {
1817                     urlPart = urlPart.substring(3);
1818                     urlPart = urlPart.trim();
1819 
1820                     if (urlPart.length() > 0 && urlPart.charAt(0) == '=') {
1821                         urlPart = urlPart.substring(1);
1822                         urlPart = urlPart.trim();
1823                     }
1824                 }
1825 
1826                 if (org.htmlunit.util.StringUtils.isBlank(urlPart)) {
1827                     //content='10; URL=' is treated as content='10'
1828                     url = getUrl();
1829                 }
1830                 else {
1831                     if (urlPart.charAt(0) == '"' || urlPart.charAt(0) == 0x27) {
1832                         urlPart = urlPart.substring(1);
1833                     }
1834                     if (urlPart.charAt(urlPart.length() - 1) == '"' || urlPart.charAt(urlPart.length() - 1) == 0x27) {
1835                         urlPart = urlPart.substring(0, urlPart.length() - 1);
1836                     }
1837                     try {
1838                         url = getFullyQualifiedUrl(urlPart);
1839                     }
1840                     catch (final MalformedURLException e) {
1841                         if (LOG.isErrorEnabled()) {
1842                             LOG.error("Malformed URL in refresh string: " + refreshString, e);
1843                         }
1844                         return;
1845                     }
1846                 }
1847             }
1848             else {
1849                 if (LOG.isErrorEnabled()) {
1850                     LOG.error("Malformed refresh string (separator after time missing): " + refreshString);
1851                 }
1852                 return;
1853             }
1854         }
1855 
1856         processRefresh(url, time);
1857     }
1858 
1859     // this is different from what is done in org.htmlunit.WebClient.loadWebResponseFromWebConnection(WebRequest, int)
1860     // because there we are directly replacing the response before loading the response into the window
1861     // here we are replacing the page in the window (maybe after some time)
1862     private void processRefresh(final URL url, final double time) throws IOException {
1863         // accessing to local resource is forbidden for security reason
1864         if (!isLocalResourceAccessAllowed(url)) {
1865             notifyIncorrectness("Not allowed to load local resource: " + url);
1866             return;
1867         }
1868 
1869         final WebClient webClient = getWebClient();
1870 
1871         final int refreshLimit = webClient.getOptions().getPageRefreshLimit();
1872         if (refreshLimit == 0) {
1873             final WebResponse webResponse = getWebResponse();
1874             throw new FailingHttpStatusCodeException("Too many redirects for "
1875                     + webResponse.getWebRequest().getUrl(), webResponse);
1876         }
1877 
1878         if (refreshLimit >= 0) {
1879             final StackTraceElement[] elements = new Exception().getStackTrace();
1880             int count = 0;
1881             final int elementCountLimit = refreshLimit > 50 ? 400 : refreshLimit > 10 ? 80 : 5;
1882             final int elementCount = elements.length;
1883 
1884             if (elementCount > elementCountLimit) {
1885                 for (int i = 0; i < elementCount; i++) {
1886                     if ("processRefresh".equals(elements[i].getMethodName())
1887                             && "org.htmlunit.html.HtmlPage".equals(elements[i].getClassName())) {
1888                         count++;
1889                         if (count >= refreshLimit) {
1890                             final WebResponse webResponse = getWebResponse();
1891                             throw new FailingHttpStatusCodeException(
1892                                             "Too many redirects (>= " + count + ") for "
1893                                                 + webResponse.getWebRequest().getUrl(), webResponse);
1894                         }
1895                     }
1896                 }
1897             }
1898         }
1899 
1900         webClient.getRefreshHandler().handleRefresh(this, url, (int) time);
1901     }
1902 
1903     /**
1904      * Returns an auto-refresh string if specified. This will look in both the meta
1905      * tags and inside the HTTP response headers.
1906      * @return the auto-refresh string
1907      */
1908     private String getRefreshStringOrNull() {
1909         final List<HtmlMeta> metaTags = getMetaTags("refresh");
1910         if (!metaTags.isEmpty()) {
1911             return metaTags.get(0).getContentAttribute().trim();
1912         }
1913         return getWebResponse().getResponseHeaderValue("Refresh");
1914     }
1915 
1916     private void processPostponedActionsIfNeeded() {
1917         if (!getWebClient().isJavaScriptEnabled()) {
1918             return;
1919         }
1920         getWebClient().getJavaScriptEngine().processPostponedActions();
1921     }
1922 
1923     /**
1924      * Executes any deferred scripts, if necessary.
1925      */
1926     private void executeDeferredScriptsIfNeeded() {
1927         if (!getWebClient().isJavaScriptEnabled()) {
1928             return;
1929         }
1930         final DomElement doc = getDocumentElement();
1931         final List<HtmlScript> scripts = new ArrayList<>();
1932 
1933         // don't call getElementsByTagName() here because it creates a live collection
1934         for (final HtmlElement elem : doc.getHtmlElementDescendants()) {
1935             if ("script".equals(elem.getLocalName()) && (elem instanceof HtmlScript script)) {
1936                 if (script.isDeferred() && script.wasParserInserted()
1937                         && ATTRIBUTE_NOT_DEFINED != script.getSrcAttribute()) {
1938                     scripts.add(script);
1939                 }
1940             }
1941         }
1942         for (final HtmlScript script : scripts) {
1943             ScriptElementSupport.executeScriptIfNeeded(script, true, true);
1944         }
1945     }
1946 
1947     /**
1948      * Deregister frames that are no longer in use.
1949      */
1950     public void deregisterFramesIfNeeded() {
1951         final List<BaseFrameElement> frameElementsCopy = new ArrayList<>(frameElements_);
1952         for (final BaseFrameElement frameElement : frameElementsCopy) {
1953             final WebWindow window = frameElement.getEnclosedWindow();
1954             getWebClient().deregisterWebWindow(window);
1955             final Page page = window.getEnclosedPage();
1956             if (page != null && page.isHtmlPage()) {
1957                 // seems quite silly, but for instance if the src attribute of an iframe is not
1958                 // set, the error only occurs when leaving the page
1959                 ((HtmlPage) page).deregisterFramesIfNeeded();
1960             }
1961         }
1962     }
1963 
1964     /**
1965      * Returns a list containing all the frames (from frame and iframe tags) in this page
1966      * in document order.
1967      * @return a list of {@link FrameWindow}
1968      */
1969     public List<FrameWindow> getFrames() {
1970         final List<BaseFrameElement> frameElements = new ArrayList<>(frameElements_);
1971         frameElements.sort(DOCUMENT_POSITION_COMPERATOR);
1972 
1973         final List<FrameWindow> list = new ArrayList<>(frameElements.size());
1974         for (final BaseFrameElement frameElement : frameElements) {
1975             list.add(frameElement.getEnclosedWindow());
1976         }
1977         return list;
1978     }
1979 
1980     /**
1981      * Returns the first frame contained in this page with the specified name.
1982      * @param name the name to search for
1983      * @return the first frame found
1984      * @throws ElementNotFoundException If no frame exist in this page with the specified name.
1985      */
1986     public FrameWindow getFrameByName(final String name) throws ElementNotFoundException {
1987         for (final BaseFrameElement frameElement : frameElements_) {
1988             final FrameWindow fw = frameElement.getEnclosedWindow();
1989             if (fw.getName().equals(name)) {
1990                 return fw;
1991             }
1992         }
1993 
1994         throw new ElementNotFoundException("frame or iframe", DomElement.NAME_ATTRIBUTE, name);
1995     }
1996 
1997     /**
1998      * Simulate pressing an access key. This may change the focus, may click buttons and may invoke
1999      * JavaScript.
2000      *
2001      * @param accessKey the key that will be pressed
2002      * @return the element that has the focus after pressing this access key or null if no element
2003      *         has the focus.
2004      * @throws IOException if an IO error occurs during the processing of this access key (this
2005      *         would only happen if the access key triggered a button which in turn caused a page load)
2006      */
2007     public DomElement pressAccessKey(final char accessKey) throws IOException {
2008         final HtmlElement element = getHtmlElementByAccessKey(accessKey);
2009         if (element != null) {
2010             element.focus();
2011             if (element instanceof HtmlAnchor
2012                     || element instanceof HtmlArea
2013                     || element instanceof HtmlButton
2014                     || element instanceof HtmlInput
2015                     || element instanceof HtmlLabel
2016                     || element instanceof HtmlLegend
2017                     || element instanceof HtmlTextArea) {
2018                 final Page newPage = element.click();
2019 
2020                 if (newPage != this && getFocusedElement() == element) {
2021                     // The page was reloaded therefore no element on this page will have the focus.
2022                     getFocusedElement().blur();
2023                 }
2024             }
2025         }
2026 
2027         return getFocusedElement();
2028     }
2029 
2030     /**
2031      * Move the focus to the next element in the tab order. To determine the specified tab
2032      * order, refer to {@link HtmlPage#getTabbableElements()}
2033      *
2034      * @return the element that has focus after calling this method
2035      */
2036     public HtmlElement tabToNextElement() {
2037         final List<HtmlElement> elements = getTabbableElements();
2038         if (elements.isEmpty()) {
2039             setFocusedElement(null);
2040             return null;
2041         }
2042 
2043         final HtmlElement elementToGiveFocus;
2044         final DomElement elementWithFocus = getFocusedElement();
2045         if (elementWithFocus == null) {
2046             elementToGiveFocus = elements.get(0);
2047         }
2048         else {
2049             final int index = elements.indexOf(elementWithFocus);
2050             if (index == -1) {
2051                 // The element with focus isn't on this page
2052                 elementToGiveFocus = elements.get(0);
2053             }
2054             else if (index == elements.size() - 1) {
2055                 // if at last jump to start
2056                 elementToGiveFocus = elements.get(0);
2057             }
2058             else {
2059                 elementToGiveFocus = elements.get(index + 1);
2060             }
2061         }
2062 
2063         setFocusedElement(elementToGiveFocus);
2064         return elementToGiveFocus;
2065     }
2066 
2067     /**
2068      * Move the focus to the previous element in the tab order. To determine the specified tab
2069      * order, refer to {@link HtmlPage#getTabbableElements()}
2070      *
2071      * @return the element that has focus after calling this method
2072      */
2073     public HtmlElement tabToPreviousElement() {
2074         final List<HtmlElement> elements = getTabbableElements();
2075         if (elements.isEmpty()) {
2076             setFocusedElement(null);
2077             return null;
2078         }
2079 
2080         final HtmlElement elementToGiveFocus;
2081         final DomElement elementWithFocus = getFocusedElement();
2082         if (elementWithFocus == null) {
2083             elementToGiveFocus = elements.get(elements.size() - 1);
2084         }
2085         else {
2086             final int index = elements.indexOf(elementWithFocus);
2087             if (index == -1) {
2088                 // The element with focus isn't on this page
2089                 elementToGiveFocus = elements.get(elements.size() - 1);
2090             }
2091             else if (index == 0) {
2092                 // first; back to the last
2093                 elementToGiveFocus = elements.get(elements.size() - 1);
2094             }
2095             else {
2096                 elementToGiveFocus = elements.get(index - 1);
2097             }
2098         }
2099 
2100         setFocusedElement(elementToGiveFocus);
2101         return elementToGiveFocus;
2102     }
2103 
2104     /**
2105      * Returns the HTML element with the specified ID. If more than one element
2106      * has this ID (not allowed by the HTML spec), then this method returns the
2107      * first one.
2108      *
2109      * @param elementId the ID value to search for
2110      * @param <E> the element type
2111      * @return the HTML element with the specified ID
2112      * @throws ElementNotFoundException if no element was found matching the specified ID
2113      */
2114     @SuppressWarnings("unchecked")
2115     public <E extends HtmlElement> E getHtmlElementById(final String elementId) throws ElementNotFoundException {
2116         final DomElement element = getElementById(elementId);
2117         if (element == null) {
2118             throw new ElementNotFoundException("*", DomElement.ID_ATTRIBUTE, elementId);
2119         }
2120         return (E) element;
2121     }
2122 
2123     /**
2124      * Returns the elements with the specified ID. If there are no elements
2125      * with the specified ID, this method returns an empty list. Please note that
2126      * the lists returned by this method are immutable.
2127      *
2128      * @param elementId the ID value to search for
2129      * @return the elements with the specified name attribute
2130      */
2131     public List<DomElement> getElementsById(final String elementId) {
2132         if (elementId != null) {
2133             ensureMappedElementsBuilt();
2134             final MappedElementIndexEntry elements = idMap_.get(elementId);
2135             if (elements != null) {
2136                 return new ArrayList<>(elements.elements());
2137             }
2138         }
2139         return Collections.emptyList();
2140     }
2141 
2142     /**
2143      * Returns the element with the specified name. If more than one element
2144      * has this name, then this method returns the first one.
2145      *
2146      * @param name the name value to search for
2147      * @param <E> the element type
2148      * @return the element with the specified name
2149      * @throws ElementNotFoundException if no element was found matching the specified name
2150      */
2151     @SuppressWarnings("unchecked")
2152     public <E extends DomElement> E getElementByName(final String name) throws ElementNotFoundException {
2153         if (name != null) {
2154             ensureMappedElementsBuilt();
2155             final MappedElementIndexEntry elements = nameMap_.get(name);
2156             if (elements != null) {
2157                 return (E) elements.first();
2158             }
2159         }
2160         throw new ElementNotFoundException("*", DomElement.NAME_ATTRIBUTE, name);
2161     }
2162 
2163     /**
2164      * Returns the elements with the specified name attribute. If there are no elements
2165      * with the specified name, this method returns an empty list. Please note that
2166      * the lists returned by this method are immutable.
2167      *
2168      * @param name the name value to search for
2169      * @return the elements with the specified name attribute
2170      */
2171     public List<DomElement> getElementsByName(final String name) {
2172         if (name != null) {
2173             ensureMappedElementsBuilt();
2174             final MappedElementIndexEntry elements = nameMap_.get(name);
2175             if (elements != null) {
2176                 return new ArrayList<>(elements.elements());
2177             }
2178         }
2179         return Collections.emptyList();
2180     }
2181 
2182     /**
2183      * Returns the elements with the specified string for their name or ID. If there are
2184      * no elements with the specified name or ID, this method returns an empty list.
2185      *
2186      * @param idAndOrName the value to search for
2187      * @return the elements with the specified string for their name or ID
2188      */
2189     public List<DomElement> getElementsByIdAndOrName(final String idAndOrName) {
2190         if (idAndOrName == null) {
2191             return Collections.emptyList();
2192         }
2193         ensureMappedElementsBuilt();
2194         final MappedElementIndexEntry list1 = idMap_.get(idAndOrName);
2195         final MappedElementIndexEntry list2 = nameMap_.get(idAndOrName);
2196         final List<DomElement> list = new ArrayList<>();
2197         if (list1 != null) {
2198             list.addAll(list1.elements());
2199         }
2200         if (list2 != null) {
2201             for (final DomElement elt : list2.elements()) {
2202                 if (!list.contains(elt)) {
2203                     list.add(elt);
2204                 }
2205             }
2206         }
2207         return list;
2208     }
2209 
2210     /**
2211      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2212      *
2213      * @param node the node that has just been added to the document
2214      */
2215     void notifyNodeAdded(final DomNode node) {
2216         if (node instanceof DomElement element1) {
2217             addMappedElement(element1, true);
2218 
2219             if (node instanceof BaseFrameElement element) {
2220                 frameElements_.add(element);
2221             }
2222 
2223             if (node.getFirstChild() != null) {
2224                 for (final Iterator<HtmlElement> iterator = node.new DescendantHtmlElementsIterator();
2225                         iterator.hasNext();) {
2226                     final HtmlElement child = iterator.next();
2227                     if (child instanceof BaseFrameElement element) {
2228                         frameElements_.add(element);
2229                     }
2230                 }
2231             }
2232 
2233             if ("base".equals(node.getNodeName())) {
2234                 // like Chrome, adding a base element checks the base url again
2235                 cspCheckedBaseHref_ = null;
2236                 calculateBase();
2237             }
2238         }
2239 
2240         if (node instanceof DomDocumentType doctype && node.getParentNode() == this) {
2241             setDocumentType(doctype);
2242         }
2243 
2244         if (!autofocusProcessed_ && node instanceof HtmlElement element) {
2245             addAutofocusCandidates(element);
2246         }
2247 
2248         node.onAddedToPage();
2249     }
2250 
2251     /**
2252      * Adds the given element and all its descendants having an {@code autofocus} attribute
2253      * to the list of autofocus candidates.
2254      *
2255      * @param element the element inserted into this page
2256      */
2257     private void addAutofocusCandidates(final HtmlElement element) {
2258         boolean added = addAutofocusCandidate(element);
2259         if (element.getFirstChild() != null) {
2260             for (final HtmlElement descendant : element.getHtmlElementDescendants()) {
2261                 added = addAutofocusCandidate(descendant) || added;
2262             }
2263         }
2264 
2265         if (added && autofocusAfterLoad_) {
2266             scheduleAutofocusProcessing();
2267         }
2268     }
2269 
2270     private boolean addAutofocusCandidate(final HtmlElement element) {
2271         if (!element.hasAttribute("autofocus")) {
2272             return false;
2273         }
2274 
2275         if (autofocusCandidates_ == null) {
2276             autofocusCandidates_ = new ArrayList<>();
2277         }
2278         else if (autofocusCandidates_.contains(element)) {
2279             return false;
2280         }
2281         autofocusCandidates_.add(element);
2282         return true;
2283     }
2284 
2285     /**
2286      * Like in the browsers, the candidates inserted after the page was loaded are not
2287      * processed immediately but a bit later.
2288      */
2289     private void scheduleAutofocusProcessing() {
2290         if (autofocusJobScheduled_) {
2291             return;
2292         }
2293 
2294         final WebWindow window = getEnclosingWindow();
2295         if (window == null || !getWebClient().isJavaScriptEnabled()) {
2296             processAutofocusCandidates();
2297             return;
2298         }
2299 
2300         autofocusJobScheduled_ = true;
2301         final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().createJavaScriptJob(0, null,
2302                 () -> {
2303                     autofocusJobScheduled_ = false;
2304                     processAutofocusCandidates();
2305                 });
2306         window.getJobManager().addJob(job, this);
2307     }
2308 
2309     /**
2310      * Focuses the first focusable autofocus candidate, if no other element has the focus.
2311      * After this, the autofocus is never used again for this page.
2312      */
2313     private void processAutofocusCandidates() {
2314         if (autofocusProcessed_ || autofocusCandidates_ == null) {
2315             return;
2316         }
2317 
2318         // an element focused already (e.g. by a script) wins
2319         if (elementWithFocus_ != null) {
2320             autofocusCandidates_ = null;
2321             autofocusProcessed_ = true;
2322             return;
2323         }
2324 
2325         while (!autofocusCandidates_.isEmpty()) {
2326             final HtmlElement candidate = autofocusCandidates_.remove(0);
2327             if (candidate.getPage() != this || !candidate.isAttachedToPage()) {
2328                 continue;
2329             }
2330 
2331             candidate.focus();
2332             if (elementWithFocus_ == candidate) {
2333                 autofocusCandidates_ = null;
2334                 autofocusProcessed_ = true;
2335                 return;
2336             }
2337         }
2338     }
2339 
2340     /**
2341      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2342      *
2343      * @param node the node that has just been removed from the tree
2344      */
2345     void notifyNodeRemoved(final DomNode node) {
2346         if (node instanceof HtmlElement element) {
2347             removeMappedElement(element, true, true);
2348 
2349             if (node instanceof BaseFrameElement) {
2350                 frameElements_.remove(node);
2351             }
2352             for (final HtmlElement child : node.getHtmlElementDescendants()) {
2353                 if (child instanceof BaseFrameElement) {
2354                     frameElements_.remove(child);
2355                 }
2356             }
2357 
2358             if ("base".equals(node.getNodeName())) {
2359                 calculateBase();
2360             }
2361             return;
2362         }
2363 
2364         if (node instanceof DomDocumentType && node == getDoctype()) {
2365             setDocumentType(null);
2366         }
2367     }
2368 
2369     /**
2370      * Adds an element to the ID and name maps, if necessary.
2371      * @param element the element to be added to the ID and name maps
2372      * @param recurse indicates if children must be added too
2373      */
2374     void addMappedElement(final DomElement element, final boolean recurse) {
2375         // Index is built lazily; skip while not built. ensureMappedElementsBuilt()
2376         // walks the tree once and populates everything on first read.
2377         if (!mappedElementsBuilt_) {
2378             return;
2379         }
2380         if (isAncestorOf(element)) {
2381             addElement(element, recurse);
2382         }
2383     }
2384 
2385     private void ensureMappedElementsBuilt() {
2386         if (mappedElementsBuilt_) {
2387             return;
2388         }
2389 
2390         final DomElement root = getDocumentElement();
2391         if (root != null) {
2392             addElement(root, true);
2393         }
2394 
2395         // Flip the flag only after the maps are populated, so a partial
2396         // failure mid-walk leaves us with built_=false and the next read
2397         // tries again rather than seeing a half-populated index.
2398         mappedElementsBuilt_ = true;
2399     }
2400 
2401     private void addElement(final DomElement element, final boolean recurse) {
2402         final String idValue = element.getAttribute(DomElement.ID_ATTRIBUTE);
2403         if (ATTRIBUTE_NOT_DEFINED != idValue) {
2404             MappedElementIndexEntry elements = idMap_.get(idValue);
2405             if (elements == null) {
2406                 elements = new MappedElementIndexEntry();
2407                 elements.add(element);
2408                 idMap_.put(idValue, elements);
2409             }
2410             else {
2411                 elements.add(element);
2412             }
2413         }
2414 
2415         final String nameValue = element.getAttribute(DomElement.NAME_ATTRIBUTE);
2416         if (ATTRIBUTE_NOT_DEFINED != nameValue) {
2417             MappedElementIndexEntry elements = nameMap_.get(nameValue);
2418             if (elements == null) {
2419                 elements = new MappedElementIndexEntry();
2420                 elements.add(element);
2421                 nameMap_.put(nameValue, elements);
2422             }
2423             else {
2424                 elements.add(element);
2425             }
2426         }
2427 
2428         if (recurse) {
2429             // poor man's approach - we don't use getChildElements()
2430             // to avoid a bunch of object constructions
2431             DomNode nextChild = element.getFirstChild();
2432             while (nextChild != null) {
2433                 if (nextChild instanceof DomElement domElement) {
2434                     addElement(domElement, true);
2435                 }
2436                 nextChild = nextChild.getNextSibling();
2437             }
2438         }
2439     }
2440 
2441     /**
2442      * Removes an element and optionally its children from the ID and name maps, if necessary.
2443      * @param element the element to be removed from the ID and name maps
2444      * @param recurse indicates if children must be removed too
2445      * @param descendant indicates of the element was descendant of this HtmlPage, but now its parent might be null
2446      */
2447     void removeMappedElement(final DomElement element, final boolean recurse, final boolean descendant) {
2448         // see addMappedElement: while the index is unbuilt, removals are also no-ops.
2449         if (!mappedElementsBuilt_) {
2450             return;
2451         }
2452         if (descendant || isAncestorOf(element)) {
2453             removeElement(element, recurse);
2454         }
2455     }
2456 
2457     private void removeElement(final DomElement element, final boolean recurse) {
2458         final String idValue = element.getAttribute(DomElement.ID_ATTRIBUTE);
2459         if (ATTRIBUTE_NOT_DEFINED != idValue) {
2460             final MappedElementIndexEntry elements = idMap_.remove(idValue);
2461             if (elements != null) {
2462                 elements.remove(element);
2463                 if (!elements.elements_.isEmpty()) {
2464                     idMap_.put(idValue, elements);
2465                 }
2466             }
2467         }
2468 
2469         final String nameValue = element.getAttribute(DomElement.NAME_ATTRIBUTE);
2470         if (ATTRIBUTE_NOT_DEFINED != nameValue) {
2471             final MappedElementIndexEntry elements = nameMap_.remove(nameValue);
2472             if (elements != null) {
2473                 elements.remove(element);
2474                 if (!elements.elements_.isEmpty()) {
2475                     nameMap_.put(nameValue, elements);
2476                 }
2477             }
2478         }
2479 
2480         if (recurse) {
2481             for (final DomElement child : element.getChildElements()) {
2482                 removeElement(child, true);
2483             }
2484         }
2485     }
2486 
2487     /**
2488      * Indicates if the attribute name indicates that the owning element is mapped.
2489      * @param document the owning document
2490      * @param attributeName the name of the attribute to consider
2491      * @return {@code true} if the owning element should be mapped in its owning page
2492      */
2493     static boolean isMappedElement(final Document document, final String attributeName) {
2494         return document instanceof HtmlPage
2495             && (DomElement.NAME_ATTRIBUTE.equals(attributeName) || DomElement.ID_ATTRIBUTE.equals(attributeName));
2496     }
2497 
2498     private void calculateBase() {
2499         final List<HtmlElement> baseElements = getDocumentElement().getStaticElementsByTagName("base");
2500 
2501         base_ = null;
2502         for (final HtmlElement baseElement : baseElements) {
2503             if (baseElement instanceof HtmlBase base) {
2504                 if (base_ != null) {
2505                     notifyIncorrectness("Multiple 'base' detected, only the first is used.");
2506                     break;
2507                 }
2508                 base_ = base;
2509             }
2510         }
2511 
2512         if (base_ != null) {
2513             // like the browsers, the base url is checked against the Content-Security-Policy
2514             // when the base element is added
2515             getBaseURL();
2516         }
2517     }
2518 
2519     /**
2520      * Loads the content of the contained frames. This is done after the page is completely loaded, to allow script
2521      * contained in the frames to reference elements from the page located after the closing &lt;/frame&gt; tag.
2522      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
2523      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to {@code true}
2524      */
2525     void loadFrames() throws FailingHttpStatusCodeException {
2526         for (final BaseFrameElement frameElement : new ArrayList<>(frameElements_)) {
2527             // test if the frame should really be loaded:
2528             // if a script has already changed its content, it should be skipped
2529             // use == and not equals(...) to identify initial content (versus URL set to "about:blank")
2530             if (frameElement.getEnclosedWindow() != null
2531                     && UrlUtils.URL_ABOUT_BLANK == frameElement.getEnclosedPage().getUrl()
2532                     && !frameElement.isContentLoaded()) {
2533                 frameElement.loadInnerPage();
2534             }
2535         }
2536     }
2537 
2538     /**
2539      * Gives a basic representation for debugging purposes.
2540      * @return a basic representation
2541      */
2542     @Override
2543     public String toString() {
2544         final StringBuilder builder = new StringBuilder()
2545             .append("HtmlPage(")
2546             .append(getUrl())
2547             .append(")@")
2548             .append(hashCode());
2549         return builder.toString();
2550     }
2551 
2552     /**
2553      * Gets the meta tag for a given {@code http-equiv} value.
2554      * @param httpEquiv the {@code http-equiv} value
2555      * @return a list of {@link HtmlMeta}
2556      */
2557     protected List<HtmlMeta> getMetaTags(final String httpEquiv) {
2558         if (getDocumentElement() == null) {
2559             return Collections.emptyList(); // weird case, for instance if document.documentElement has been removed
2560         }
2561         final List<HtmlMeta> tags = getDocumentElement().getStaticElementsByTagName("meta");
2562         final List<HtmlMeta> foundTags = new ArrayList<>();
2563         for (final HtmlMeta htmlMeta : tags) {
2564             if (httpEquiv.equalsIgnoreCase(htmlMeta.getHttpEquivAttribute())) {
2565                 foundTags.add(htmlMeta);
2566             }
2567         }
2568         return foundTags;
2569     }
2570 
2571     /**
2572      * Creates a clone of this instance, and clears cached state to be not shared with the original.
2573      *
2574      * @return a clone of this instance
2575      */
2576     @Override
2577     protected HtmlPage clone() {
2578         final HtmlPage result = (HtmlPage) super.clone();
2579         result.elementWithFocus_ = null;
2580         result.autofocusCandidates_ = null;
2581         result.autofocusProcessed_ = true;
2582         result.autofocusJobScheduled_ = false;
2583 
2584         result.idMap_ = new ConcurrentHashMap<>();
2585         result.nameMap_ = new ConcurrentHashMap<>();
2586         result.mappedElementsBuilt_ = false;
2587 
2588         result.parserCount_ = new AtomicInteger();
2589         result.snippetParserCount_ = new ThreadLocal<>();
2590 
2591         return result;
2592     }
2593 
2594     /**
2595      * {@inheritDoc}
2596      */
2597     @Override
2598     public HtmlPage cloneNode(final boolean deep) {
2599         // we need the ScriptObject clone before cloning the kids.
2600         final HtmlPage result = (HtmlPage) super.cloneNode(false);
2601         if (getWebClient().isJavaScriptEnabled()) {
2602             final HtmlUnitScriptable jsObjClone = getScriptableObject().clone();
2603             jsObjClone.setDomNode(result);
2604         }
2605 
2606         // if deep, clone the kids too, and re initialize parts of the clone
2607         if (deep) {
2608             // this was previously synchronized but that makes not sense, why
2609             // lock the source against a copy only one has a reference too,
2610             // because result is a local reference
2611             result.attributeListeners_ = null;
2612 
2613             result.selectionRanges_ = new ArrayList<>(3);
2614             // the original one is synchronized so we should do that here too, shouldn't we?
2615             result.afterLoadActions_ = Collections.synchronizedList(new ArrayList<>());
2616             result.frameElements_ = new ArrayList<>();
2617             for (DomNode child = getFirstChild(); child != null; child = child.getNextSibling()) {
2618                 result.appendChild(child.cloneNode(true));
2619             }
2620         }
2621         return result;
2622     }
2623 
2624     /**
2625      * Adds an HtmlAttributeChangeListener to the listener list.
2626      * The listener is registered for all attributes of all HtmlElements contained in this page.
2627      *
2628      * @param listener the attribute change listener to be added
2629      * @see #removeHtmlAttributeChangeListener(HtmlAttributeChangeListener)
2630      */
2631     public void addHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
2632         WebAssert.notNull("listener", listener);
2633         synchronized (lock_) {
2634             if (attributeListeners_ == null) {
2635                 attributeListeners_ = new LinkedHashSet<>();
2636             }
2637             attributeListeners_.add(listener);
2638         }
2639     }
2640 
2641     /**
2642      * Removes an HtmlAttributeChangeListener from the listener list.
2643      * This method should be used to remove HtmlAttributeChangeListener that were registered
2644      * for all attributes of all HtmlElements contained in this page.
2645      *
2646      * @param listener the attribute change listener to be removed
2647      * @see #addHtmlAttributeChangeListener(HtmlAttributeChangeListener)
2648      */
2649     public void removeHtmlAttributeChangeListener(final HtmlAttributeChangeListener listener) {
2650         WebAssert.notNull("listener", listener);
2651         synchronized (lock_) {
2652             if (attributeListeners_ != null) {
2653                 attributeListeners_.remove(listener);
2654             }
2655         }
2656     }
2657 
2658     /**
2659      * Notifies all registered listeners for the given event to add an attribute.
2660      * @param event the event to fire
2661      */
2662     void fireHtmlAttributeAdded(final HtmlAttributeChangeEvent event) {
2663         final List<HtmlAttributeChangeListener> listeners = safeGetAttributeListeners();
2664         if (listeners != null) {
2665             for (final HtmlAttributeChangeListener listener : listeners) {
2666                 listener.attributeAdded(event);
2667             }
2668         }
2669     }
2670 
2671     /**
2672      * Notifies all registered listeners for the given event to replace an attribute.
2673      * @param event the event to fire
2674      */
2675     void fireHtmlAttributeReplaced(final HtmlAttributeChangeEvent event) {
2676         final List<HtmlAttributeChangeListener> listeners = safeGetAttributeListeners();
2677         if (listeners != null) {
2678             for (final HtmlAttributeChangeListener listener : listeners) {
2679                 listener.attributeReplaced(event);
2680             }
2681         }
2682     }
2683 
2684     /**
2685      * Notifies all registered listeners for the given event to remove an attribute.
2686      * @param event the event to fire
2687      */
2688     void fireHtmlAttributeRemoved(final HtmlAttributeChangeEvent event) {
2689         final List<HtmlAttributeChangeListener> listeners = safeGetAttributeListeners();
2690         if (listeners != null) {
2691             for (final HtmlAttributeChangeListener listener : listeners) {
2692                 listener.attributeRemoved(event);
2693             }
2694         }
2695     }
2696 
2697     private List<HtmlAttributeChangeListener> safeGetAttributeListeners() {
2698         synchronized (lock_) {
2699             if (attributeListeners_ != null) {
2700                 return new ArrayList<>(attributeListeners_);
2701             }
2702             return null;
2703         }
2704     }
2705 
2706     /**
2707      * {@inheritDoc}
2708      */
2709     @Override
2710     protected void checkChildHierarchy(final org.w3c.dom.Node newChild) throws DOMException {
2711         if (newChild instanceof Element) {
2712             if (getDocumentElement() != null) {
2713                 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
2714                     "The Document may only have a single child Element.");
2715             }
2716         }
2717         else if (newChild instanceof DocumentType) {
2718             if (getDoctype() != null) {
2719                 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
2720                     "The Document may only have a single child DocumentType.");
2721             }
2722         }
2723         else if (!(newChild instanceof Comment || newChild instanceof ProcessingInstruction)) {
2724             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
2725                 "The Document may not have a child of this type: " + newChild.getNodeType());
2726         }
2727         super.checkChildHierarchy(newChild);
2728     }
2729 
2730     /**
2731      * Returns {@code true} if an HTML parser is operating on this page, adding content to it.
2732      * @return {@code true} if an HTML parser is operating on this page, adding content to it
2733      */
2734     public boolean isBeingParsed() {
2735         return parserCount_.get() > 0;
2736     }
2737 
2738     /**
2739      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2740      *
2741      * Called by the HTML parser to let the page know that it has started parsing some content for this page.
2742      */
2743     public void registerParsingStart() {
2744         parserCount_.incrementAndGet();
2745     }
2746 
2747     /**
2748      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2749      *
2750      * Called by the HTML parser to let the page know that it has finished parsing some content for this page.
2751      */
2752     public void registerParsingEnd() {
2753         parserCount_.decrementAndGet();
2754     }
2755 
2756     /**
2757      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2758      *
2759      * Returns {@code true} if an HTML parser of the current thread is parsing a non-inline HTML snippet
2760      * to add content to this page. Non-inline content is content that is parsed for the page, but not in the
2761      * same stream as the page itself -- basically anything other than <code>document.write()</code>
2762      * or <code>document.writeln()</code>: <code>innerHTML</code>, <code>outerHTML</code>,
2763      * <code>document.createElement()</code>, etc.
2764      *
2765      * @return {@code true} if an HTML parser of the current thread is parsing a non-inline HTML snippet
2766      *         to add content to this page
2767      */
2768     public boolean isParsingHtmlSnippet() {
2769         final SnippetParserCount count = snippetParserCount_.get();
2770         return count != null && count.snippet_ > 0;
2771     }
2772 
2773     /**
2774      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2775      *
2776      * Called by the HTML parser to let the page know that it has started parsing a non-inline HTML snippet.
2777      */
2778     public void registerSnippetParsingStart() {
2779         updateSnippetParserCount(1, 0);
2780     }
2781 
2782     /**
2783      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2784      *
2785      * Called by the HTML parser to let the page know that it has finished parsing a non-inline HTML snippet.
2786      */
2787     public void registerSnippetParsingEnd() {
2788         updateSnippetParserCount(-1, 0);
2789     }
2790 
2791     /**
2792      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2793      *
2794      * Returns {@code true} if an HTML parser of the current thread is parsing an inline HTML snippet
2795      * to add content to this page. Inline content is content inserted into the parser stream dynamically
2796      * while the page is being parsed (i.e. <code>document.write()</code> or <code>document.writeln()</code>).
2797      *
2798      * @return {@code true} if an HTML parser of the current thread is parsing an inline HTML snippet
2799      *         to add content to this page
2800      */
2801     public boolean isParsingInlineHtmlSnippet() {
2802         final SnippetParserCount count = snippetParserCount_.get();
2803         return count != null && count.inline_ > 0;
2804     }
2805 
2806     /**
2807      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2808      *
2809      * Called by the HTML parser to let the page know that it has started parsing an inline HTML snippet.
2810      */
2811     public void registerInlineSnippetParsingStart() {
2812         updateSnippetParserCount(0, 1);
2813     }
2814 
2815     /**
2816      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2817      *
2818      * Called by the HTML parser to let the page know that it has finished parsing an inline HTML snippet.
2819      */
2820     public void registerInlineSnippetParsingEnd() {
2821         updateSnippetParserCount(0, -1);
2822     }
2823 
2824     private void updateSnippetParserCount(final int snippetDelta, final int inlineDelta) {
2825         SnippetParserCount count = snippetParserCount_.get();
2826         if (count == null) {
2827             count = new SnippetParserCount();
2828             snippetParserCount_.set(count);
2829         }
2830         count.snippet_ += snippetDelta;
2831         count.inline_ += inlineDelta;
2832 
2833         // no leftovers in the thread
2834         if (count.snippet_ <= 0 && count.inline_ <= 0) {
2835             snippetParserCount_.remove();
2836         }
2837     }
2838 
2839     /**
2840      * Refreshes the page by sending the same parameters as previously sent to get this page.
2841      * @return the newly loaded page.
2842      * @throws IOException if an IO problem occurs
2843      */
2844     public Page refresh() throws IOException {
2845         return getWebClient().getPage(getWebResponse().getWebRequest());
2846     }
2847 
2848     /**
2849      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2850      * <p>
2851      * Parses the given string as would it belong to the content being parsed
2852      * at the current parsing position
2853      * </p>
2854      * @param string the HTML code to write in place
2855      */
2856     public void writeInParsedStream(final String string) {
2857         getDOMBuilder().pushInputString(string);
2858     }
2859 
2860     /**
2861      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2862      *
2863      * Sets the builder to allow page to send content from document.write(ln) calls.
2864      * @param htmlUnitDOMBuilder the builder
2865      */
2866     public void setDOMBuilder(final HTMLParserDOMBuilder htmlUnitDOMBuilder) {
2867         domBuilder_ = htmlUnitDOMBuilder;
2868     }
2869 
2870     /**
2871      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2872      *
2873      * Returns the current builder.
2874      * @return the current builder
2875      */
2876     public HTMLParserDOMBuilder getDOMBuilder() {
2877         return domBuilder_;
2878     }
2879 
2880     /**
2881      * <p>Returns all namespaces defined in the root element of this page.</p>
2882      * <p>The default namespace has a key of an empty string.</p>
2883      * @return all namespaces defined in the root element of this page
2884      */
2885     public Map<String, String> getNamespaces() {
2886         final org.w3c.dom.NamedNodeMap attributes = getDocumentElement().getAttributes();
2887         final Map<String, String> namespaces = new HashMap<>();
2888         for (int i = 0; i < attributes.getLength(); i++) {
2889             final Attr attr = (Attr) attributes.item(i);
2890             String name = attr.getName();
2891             if (name.startsWith("xmlns")) {
2892                 int startPos = 5;
2893                 if (name.length() > 5 && name.charAt(5) == ':') {
2894                     startPos = 6;
2895                 }
2896                 name = name.substring(startPos);
2897                 namespaces.put(name, attr.getValue());
2898             }
2899         }
2900         return namespaces;
2901     }
2902 
2903     /**
2904      * {@inheritDoc}
2905      */
2906     @Override
2907     public void setDocumentType(final DocumentType type) {
2908         super.setDocumentType(type);
2909     }
2910 
2911     /**
2912      * Saves the current page, with all images, to the specified location.
2913      * The default behavior removes all script elements.
2914      *
2915      * @param file file to write this page into
2916      * @throws IOException If an error occurs
2917      */
2918     public void save(final File file) throws IOException {
2919         new XmlSerializer().save(this, file);
2920     }
2921 
2922     /**
2923      * Returns whether the current page mode is in {@code quirks mode} or in {@code standards mode}.
2924      * @return true for {@code quirks mode}, false for {@code standards mode}
2925      */
2926     public boolean isQuirksMode() {
2927         return "BackCompat".equals(((HTMLDocument) getScriptableObject()).getCompatMode());
2928     }
2929 
2930     /**
2931      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2932      * {@inheritDoc}
2933      */
2934     @Override
2935     public boolean isAttachedToPage() {
2936         return true;
2937     }
2938 
2939     /**
2940      * {@inheritDoc}
2941      */
2942     @Override
2943     public boolean isHtmlPage() {
2944         return true;
2945     }
2946 
2947     /**
2948      * The base URL used to resolve relative URLs.
2949      * @return the base URL
2950      */
2951     public URL getBaseURL() {
2952         if (base_ == null) {
2953             return getFallbackBaseURL();
2954         }
2955 
2956         final String href = base_.getHrefAttribute().trim();
2957         if (org.htmlunit.util.StringUtils.isEmptyOrNull(href)) {
2958             return getUrl();
2959         }
2960 
2961         final URL baseUrl = resolveBaseHref(href);
2962         if (baseUrl == null) {
2963             return getUrl();
2964         }
2965         if (!isBaseAllowedByContentSecurityPolicy(href, baseUrl)) {
2966             return getFallbackBaseURL();
2967         }
2968         return baseUrl;
2969     }
2970 
2971     /**
2972      * Checks the url of the base element against the Content-Security-Policy (base-uri);
2973      * the check is done only once for every href value.
2974      */
2975     private boolean isBaseAllowedByContentSecurityPolicy(final String href, final URL baseUrl) {
2976         if (!href.equals(cspCheckedBaseHref_)) {
2977             cspCheckedBaseHref_ = href;
2978             cspBaseAllowed_ = ContentSecurityPolicy.allowsBaseUri(this, baseUrl);
2979         }
2980         return cspBaseAllowed_;
2981     }
2982 
2983     /**
2984      * Returns the base url used if there is no (allowed) base element.
2985      */
2986     private URL getFallbackBaseURL() {
2987         URL baseUrl = getUrl();
2988         final WebWindow window = getEnclosingWindow();
2989         final boolean frame = window != null && window != window.getTopWindow();
2990         if (frame) {
2991             // the base url of a srcdoc document is the base url of the parent document
2992             if (UrlUtils.ABOUT_SRCDOC.equals(baseUrl.toExternalForm())
2993                     && window.getParentWindow().getEnclosedPage() instanceof HtmlPage parentPage) {
2994                 return parentPage.getBaseURL();
2995             }
2996 
2997             final boolean frameSrcIsNotSet = baseUrl == UrlUtils.URL_ABOUT_BLANK;
2998             final boolean frameSrcIsJs = "javascript".equals(baseUrl.getProtocol());
2999             if (frameSrcIsNotSet || frameSrcIsJs) {
3000                 baseUrl = window.getTopWindow().getEnclosedPage().getWebResponse()
3001                     .getWebRequest().getUrl();
3002             }
3003         }
3004         else if (baseUrl_ != null) {
3005             baseUrl = baseUrl_;
3006         }
3007         return baseUrl;
3008     }
3009 
3010     /**
3011      * Resolves the href of the base element.
3012      *
3013      * @return the resolved url or {@code null} if the href is invalid
3014      */
3015     private URL resolveBaseHref(final String href) {
3016         final URL url = getUrl();
3017         try {
3018             if (href.startsWith("http://") || href.startsWith("https://")) {
3019                 return new URL(href);
3020             }
3021             // an absolute url with another scheme (e.g. file:)
3022             final int colon = href.indexOf(':');
3023             if (colon > 0 && UrlUtils.isValidScheme(href.substring(0, colon))) {
3024                 return UrlUtils.toUrlUnsafe(href);
3025             }
3026             if (href.startsWith("//")) {
3027                 return new URL("%s:%s".formatted(url.getProtocol(), href));
3028             }
3029             if (href.length() > 0 && href.charAt(0) == '/') {
3030                 final int port = Window.getPort(url);
3031                 return new URL("%s://%s:%d%s".formatted(url.getProtocol(), url.getHost(), port, href));
3032             }
3033             if (url.toString().endsWith("/")) {
3034                 return new URL("%s%s".formatted(url, href));
3035             }
3036             return new URL(UrlUtils.resolveUrl(url, href));
3037         }
3038         catch (final MalformedURLException e) {
3039             notifyIncorrectness("Invalid base url: \"" + href + "\", ignoring it");
3040             return null;
3041         }
3042     }
3043 
3044     /**
3045      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3046      *
3047      * Adds an {@link AutoCloseable}, which would be closed during the {@link #cleanUp()}.
3048      * @param autoCloseable the autoclosable
3049      */
3050     public void addAutoCloseable(final AutoCloseable autoCloseable) {
3051         if (autoCloseable == null) {
3052             return;
3053         }
3054 
3055         if (autoCloseableList_ == null) {
3056             autoCloseableList_ = new ArrayList<>();
3057         }
3058         autoCloseableList_.add(autoCloseable);
3059     }
3060 
3061     /**
3062      * {@inheritDoc}
3063      */
3064     @Override
3065     public boolean handles(final Event event) {
3066         if (Event.TYPE_BLUR.equals(event.getType()) || Event.TYPE_FOCUS.equals(event.getType())) {
3067             return true;
3068         }
3069         return super.handles(event);
3070     }
3071 
3072     /**
3073      * Sets the {@link ElementFromPointHandler}.
3074      * @param elementFromPointHandler the handler
3075      */
3076     public void setElementFromPointHandler(final ElementFromPointHandler elementFromPointHandler) {
3077         elementFromPointHandler_ = elementFromPointHandler;
3078     }
3079 
3080     /**
3081      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3082      *
3083      * Returns the element for the specified x coordinate and the specified y coordinate.
3084      *
3085      * @param x the x offset, in pixels
3086      * @param y the y offset, in pixels
3087      * @return the element for the specified x coordinate and the specified y coordinate
3088      */
3089     public HtmlElement getElementFromPoint(final int x, final int y) {
3090         if (elementFromPointHandler_ == null) {
3091             if (LOG.isWarnEnabled()) {
3092                 LOG.warn("ElementFromPointHandler was not specicifed for " + this);
3093             }
3094             if (x <= 0 || y <= 0) {
3095                 return null;
3096             }
3097             return getBody();
3098         }
3099         return elementFromPointHandler_.getElementFromPoint(this, x, y);
3100     }
3101 
3102     /**
3103      * Moves the focus to the specified element. This will trigger any relevant JavaScript
3104      * event handlers.
3105      *
3106      * @param newElement the element that will receive the focus, use {@code null} to remove focus from any element
3107      * @return true if the specified element now has the focus
3108      * @see #getFocusedElement()
3109      */
3110     public boolean setFocusedElement(final DomElement newElement) {
3111         return setFocusedElement(newElement, false);
3112     }
3113 
3114     /**
3115      * Moves the focus to the specified element. This will trigger any relevant JavaScript
3116      * event handlers.
3117      *
3118      * @param newElement the element that will receive the focus, use {@code null} to remove focus from any element
3119      * @param windowActivated - whether the enclosing window got focus resulting in specified element getting focus
3120      * @return true if the specified element now has the focus
3121      * @see #getFocusedElement()
3122      */
3123     public boolean setFocusedElement(final DomElement newElement, final boolean windowActivated) {
3124         if (elementWithFocus_ == newElement && !windowActivated) {
3125             // nothing to do
3126             return true;
3127         }
3128 
3129         final DomElement oldFocusedElement = elementWithFocus_;
3130         elementWithFocus_ = null;
3131 
3132         if (!windowActivated) {
3133             if (oldFocusedElement != null) {
3134                 oldFocusedElement.removeFocus();
3135                 oldFocusedElement.fireEvent(Event.TYPE_BLUR);
3136 
3137                 oldFocusedElement.fireEvent(Event.TYPE_FOCUS_OUT);
3138             }
3139         }
3140 
3141         elementWithFocus_ = newElement;
3142 
3143         // use newElement in the code below because element elementWithFocus_
3144         // might be changed by another thread
3145         if (newElement != null) {
3146             newElement.focus();
3147             newElement.fireEvent(Event.TYPE_FOCUS);
3148 
3149             newElement.fireEvent(Event.TYPE_FOCUS_IN);
3150         }
3151 
3152         // If a page reload happened as a result of the focus change then obviously this
3153         // element will not have the focus because its page has gone away.
3154         return this == getEnclosingWindow().getEnclosedPage();
3155     }
3156 
3157     /**
3158      * Returns the element with the focus or null if no element has the focus.
3159      * @return the element with focus or null
3160      * @see #setFocusedElement(DomElement)
3161      */
3162     public DomElement getFocusedElement() {
3163         return elementWithFocus_;
3164     }
3165 
3166     /**
3167      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
3168      *
3169      * Sets the element with focus.
3170      * @param elementWithFocus the element with focus
3171      */
3172     public void setElementWithFocus(final DomElement elementWithFocus) {
3173         elementWithFocus_ = elementWithFocus;
3174     }
3175 
3176     /**
3177      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
3178      * Returns the currently active element.
3179      *
3180      * @return the element that currently has focus, or the document's
3181      *         {@code body} element if no element has focus, or {@code null}
3182      *         if the document has no {@code body} element
3183      */
3184     public HtmlElement getActiveElement() {
3185         final DomElement activeElement = getFocusedElement();
3186         if (activeElement instanceof HtmlElement element) {
3187             return element;
3188         }
3189 
3190         final HtmlElement body = getBody();
3191         if (body != null) {
3192             return body;
3193         }
3194         return null;
3195     }
3196 
3197     /**
3198      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
3199      *
3200      * <p>Returns the page's current selection ranges.</p>
3201      *
3202      * @return the page's current selection ranges
3203      */
3204     public List<SimpleRange> getSelectionRanges() {
3205         return selectionRanges_;
3206     }
3207 
3208     /**
3209      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
3210      *
3211      * <p>Makes the specified selection range the *only* selection range on this page.</p>
3212      *
3213      * @param selectionRange the selection range
3214      */
3215     public void setSelectionRange(final SimpleRange selectionRange) {
3216         selectionRanges_.clear();
3217         selectionRanges_.add(selectionRange);
3218     }
3219 
3220     /**
3221      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3222      *
3223      * Execute a Function in the given context.
3224      *
3225      * @param function the JavaScript Function to call
3226      * @param thisObject the "this" object to be used during invocation
3227      * @param args the arguments to pass into the call
3228      * @param htmlElement the HTML element for which this script is being executed
3229      *        This element will be the context during the JavaScript execution. If null,
3230      *        the context will default to the page.
3231      * @return a ScriptResult which will contain both the current page (which may be different from
3232      *        the previous page) and a JavaScript result object.
3233      */
3234     public ScriptResult executeJavaScriptFunction(final Object function, final Object thisObject,
3235             final Object[] args, final DomNode htmlElement) {
3236         if (!getWebClient().isJavaScriptEnabled()) {
3237             return new ScriptResult(null);
3238         }
3239 
3240         final JavaScriptEngine engine = (JavaScriptEngine) getWebClient().getJavaScriptEngine();
3241         final Object result = engine.callFunction(this,
3242                                 (Function) function, (Scriptable) thisObject, args, htmlElement);
3243 
3244         return new ScriptResult(result);
3245     }
3246 
3247     private void writeObject(final ObjectOutputStream oos) throws IOException {
3248         oos.defaultWriteObject();
3249         oos.writeObject(originalCharset_ == null ? null : originalCharset_.name());
3250     }
3251 
3252     private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
3253         ois.defaultReadObject();
3254         final String charsetName = (String) ois.readObject();
3255         if (charsetName != null) {
3256             originalCharset_ = Charset.forName(charsetName);
3257         }
3258         snippetParserCount_ = new ThreadLocal<>();
3259     }
3260 
3261     /**
3262      * {@inheritDoc}
3263      */
3264     @Override
3265     public void setNodeValue(final String value) {
3266         // Default behavior is to do nothing, overridden in some subclasses
3267     }
3268 
3269     /**
3270      * {@inheritDoc}
3271      */
3272     @Override
3273     public void setPrefix(final String prefix) {
3274         // Empty.
3275     }
3276 
3277     /**
3278      * {@inheritDoc}
3279      */
3280     @Override
3281     public void clearComputedStyles() {
3282         if (computedStylesCache_ != null) {
3283             computedStylesCache_.clear();
3284         }
3285     }
3286 
3287     /**
3288      * {@inheritDoc}
3289      */
3290     @Override
3291     public void clearComputedStyles(final DomElement element) {
3292         if (computedStylesCache_ != null) {
3293             computedStylesCache_.remove(element);
3294         }
3295     }
3296 
3297     /**
3298      * {@inheritDoc}
3299      */
3300     @Override
3301     public void clearComputedStylesUpToRoot(final DomElement element) {
3302         if (computedStylesCache_ != null) {
3303             computedStylesCache_.remove(element);
3304 
3305             DomNode parent = element.getParentNode();
3306             while (parent != null) {
3307                 computedStylesCache_.remove(parent);
3308                 parent = parent.getParentNode();
3309             }
3310         }
3311     }
3312 
3313     /**
3314      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3315      *
3316      * @param element the element to clear its cache
3317      * @param normalizedPseudo the pseudo attribute
3318      * @return the cached ComputedCssStyleDeclaration object or null
3319      */
3320     public ComputedCssStyleDeclaration getStyleFromCache(final DomElement element,
3321             final String normalizedPseudo) {
3322         return getCssPropertiesCache().get(element, normalizedPseudo);
3323     }
3324 
3325     /**
3326      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3327      *
3328      * Caches a ComputedCssStyleDeclaration object.
3329      * @param element the element to clear its cache
3330      * @param normalizedPseudo the pseudo attribute
3331      * @param style the ComputedCssStyleDeclaration to cache
3332      */
3333     public void putStyleIntoCache(final DomElement element, final String normalizedPseudo,
3334             final ComputedCssStyleDeclaration style) {
3335         getCssPropertiesCache().put(element, normalizedPseudo, style);
3336     }
3337 
3338     /**
3339      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3340      *
3341      * @return a list of all styles from this page (&lt;style&gt; and &lt;link rel=stylesheet&gt;).
3342      *         This returns an empty list if css support is disabled in the web client options.
3343      */
3344     public List<CssStyleSheet> getStyleSheets() {
3345         final List<CssStyleSheet> styles = new ArrayList<>();
3346         if (getWebClient().getOptions().isCssEnabled()) {
3347             for (final HtmlElement htmlElement : getHtmlElementDescendants()) {
3348                 if (htmlElement instanceof HtmlStyle style) {
3349                     styles.add(style.getSheet());
3350                     continue;
3351                 }
3352 
3353                 if (htmlElement instanceof HtmlLink link) {
3354                     if (link.isStyleSheetLink()) {
3355                         styles.add(link.getSheet());
3356                     }
3357                 }
3358             }
3359         }
3360         return styles;
3361     }
3362 
3363     /**
3364      * Returns the computed styles cache for this page.
3365      *
3366      * @return the computed styles cache for this page
3367      */
3368     private ComputedStylesCache getCssPropertiesCache() {
3369         if (computedStylesCache_ == null) {
3370             computedStylesCache_ = new ComputedStylesCache();
3371 
3372             // maintain the style cache
3373             final DomHtmlAttributeChangeListenerImpl listener = new DomHtmlAttributeChangeListenerImpl();
3374             addDomChangeListener(listener);
3375             addHtmlAttributeChangeListener(listener);
3376         }
3377         return computedStylesCache_;
3378     }
3379 
3380     /**
3381      * <p>Listens for changes anywhere in the document and evicts cached computed styles whenever something relevant
3382      * changes. Note that the very lazy way of doing this (completely clearing the cache every time something happens)
3383      * results in very meager performance gains. In order to get good (but still correct) performance, we need to be
3384      * a little smarter.</p>
3385      *
3386      * <p>CSS 2.1 has the following <a href="http://www.w3.org/TR/CSS21/selector.html">selector types</a> (where "SN" is
3387      * shorthand for "the selected node"):</p>
3388      *
3389      * <ol>
3390      *   <li><em>Universal</em> (i.e. "*"): Affected by the removal of SN from the document.</li>
3391      *   <li><em>Type</em> (i.e. "div"): Affected by the removal of SN from the document.</li>
3392      *   <li><em>Descendant</em> (i.e. "div span"): Affected by changes to SN or to any of its ancestors.</li>
3393      *   <li><em>Child</em> (i.e. "div &gt; span"): Affected by changes to SN or to its parent.</li>
3394      *   <li><em>Adjacent Sibling</em> (i.e. "table + p"): Affected by changes to SN or its previous sibling.</li>
3395      *   <li><em>Attribute</em> (i.e. "div.up, div[class~=up]"): Affected by changes to an attribute of SN.</li>
3396      *   <li><em>ID</em> (i.e. "#header"): Affected by changes to the <code>id</code> attribute of SN.</li>
3397      *   <li><em>Pseudo-Elements and Pseudo-Classes</em> (i.e. "p:first-child"): Affected by changes to parent.</li>
3398      * </ol>
3399      *
3400      * <p>Together, these rules dictate that the smart (but still lazy) way of removing elements from the computed style
3401      * cache is as follows -- whenever a node changes in any way, the cache needs to be cleared of styles for nodes
3402      * which:</p>
3403      *
3404      * <ul>
3405      *   <li>are actually the same node as the node that changed</li>
3406      *   <li>are siblings of the node that changed</li>
3407      *   <li>are descendants of the node that changed</li>
3408      * </ul>
3409      *
3410      * <p>Additionally, whenever a <code>style</code> node or a <code>link</code> node
3411      * with <code>rel=stylesheet</code> is added or
3412      * removed, all elements should be removed from the computed style cache.</p>
3413      */
3414     private class DomHtmlAttributeChangeListenerImpl implements DomChangeListener, HtmlAttributeChangeListener {
3415 
3416         /**
3417          * Ctor.
3418          */
3419         DomHtmlAttributeChangeListenerImpl() {
3420             super();
3421         }
3422 
3423         /**
3424          * {@inheritDoc}
3425          */
3426         @Override
3427         public void nodeAdded(final DomChangeEvent event) {
3428             nodeChanged(event.getChangedNode(), null);
3429         }
3430 
3431         /**
3432          * {@inheritDoc}
3433          */
3434         @Override
3435         public void nodeDeleted(final DomChangeEvent event) {
3436             nodeChanged(event.getChangedNode(), null);
3437         }
3438 
3439         /**
3440          * {@inheritDoc}
3441          */
3442         @Override
3443         public void attributeAdded(final HtmlAttributeChangeEvent event) {
3444             nodeChanged(event.getHtmlElement(), event.getName());
3445         }
3446 
3447         /**
3448          * {@inheritDoc}
3449          */
3450         @Override
3451         public void attributeRemoved(final HtmlAttributeChangeEvent event) {
3452             nodeChanged(event.getHtmlElement(), event.getName());
3453         }
3454 
3455         /**
3456          * {@inheritDoc}
3457          */
3458         @Override
3459         public void attributeReplaced(final HtmlAttributeChangeEvent event) {
3460             nodeChanged(event.getHtmlElement(), event.getName());
3461         }
3462 
3463         private void nodeChanged(final DomNode changedNode, final String attribName) {
3464             // If a stylesheet was changed, all of our calculations could be off; clear the cache.
3465             if (changedNode instanceof HtmlStyle) {
3466                 clearComputedStyles();
3467                 return;
3468             }
3469             if (changedNode instanceof HtmlLink link) {
3470                 if (link.isStyleSheetLink()) {
3471                     clearComputedStyles();
3472                     return;
3473                 }
3474             }
3475 
3476             // Apparently it wasn't a stylesheet that changed; be semi-smart about what we evict and when.
3477             // null means that a node was added/removed; we always have to take care of this for the parents
3478             final boolean clearParents = attribName == null || ATTRIBUTES_AFFECTING_PARENT.contains(attribName);
3479             if (computedStylesCache_ != null) {
3480                 computedStylesCache_.nodeChanged(changedNode, clearParents);
3481             }
3482         }
3483     }
3484 
3485     /**
3486      * The nesting depth of the snippet parsers of one thread for this page.
3487      */
3488     private static final class SnippetParserCount {
3489         private int snippet_;
3490         private int inline_;
3491     }
3492 
3493     /**
3494      * Cache computed styles when possible, because their calculation is very expensive.
3495      * We use a weak hash map because we don't want this cache to be the only reason
3496      * nodes are kept around in the JVM, if all other references to them are gone.
3497      * The class is private; no one else can lock on an instance, therefore method level
3498      * synchronization is fine here.
3499      */
3500     @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
3501     private static final class ComputedStylesCache implements Serializable {
3502         private transient WeakHashMap<DomElement, Map<String, ComputedCssStyleDeclaration>>
3503                     computedStyles_ = new WeakHashMap<>();
3504 
3505         /**
3506          * Ctor.
3507          */
3508         ComputedStylesCache() {
3509             super();
3510         }
3511 
3512         public synchronized ComputedCssStyleDeclaration get(final DomElement element,
3513                 final String normalizedPseudo) {
3514             final Map<String, ComputedCssStyleDeclaration> elementMap = computedStyles_.get(element);
3515             if (elementMap != null) {
3516                 return elementMap.get(normalizedPseudo);
3517             }
3518             return null;
3519         }
3520 
3521         public synchronized void put(final DomElement element,
3522                 final String normalizedPseudo, final ComputedCssStyleDeclaration style) {
3523             final Map<String, ComputedCssStyleDeclaration>
3524                     elementMap = computedStyles_.computeIfAbsent(element, k -> new WeakHashMap<>());
3525             elementMap.put(normalizedPseudo, style);
3526         }
3527 
3528         public synchronized void nodeChanged(final DomNode changed, final boolean clearParents) {
3529             final Iterator<Map.Entry<DomElement, Map<String, ComputedCssStyleDeclaration>>>
3530                     i = computedStyles_.entrySet().iterator();
3531             while (i.hasNext()) {
3532                 final Map.Entry<DomElement, Map<String, ComputedCssStyleDeclaration>> entry = i.next();
3533                 final DomElement node = entry.getKey();
3534                 if (changed == node
3535                     || changed.getParentNode() == node.getParentNode()
3536                     || changed.isAncestorOf(node)
3537                     || clearParents && node.isAncestorOf(changed)) {
3538                     i.remove();
3539                 }
3540             }
3541 
3542             // maybe this is a better solution but I have to think a bit more about this
3543             //
3544             //            if (computedStyles_.isEmpty()) {
3545             //                return;
3546             //            }
3547             //
3548             //            // remove all siblings
3549             //            DomNode parent = changed.getParentNode();
3550             //            if (parent != null) {
3551             //                for (DomNode sibling : parent.getChildNodes()) {
3552             //                    computedStyles_.remove(sibling.getScriptableObject());
3553             //                }
3554             //
3555             //                if (clearParents) {
3556             //                    // remove all parents
3557             //                    while (parent != null) {
3558             //                        computedStyles_.remove(parent.getScriptableObject());
3559             //                        parent = parent.getParentNode();
3560             //                    }
3561             //                }
3562             //            }
3563             //
3564             //            // remove changed itself and all descendants
3565             //            computedStyles_.remove(changed.getScriptableObject());
3566             //            for (DomNode descendant : changed.getDescendants()) {
3567             //                computedStyles_.remove(descendant.getScriptableObject());
3568             //            }
3569         }
3570 
3571         public synchronized void clear() {
3572             computedStyles_.clear();
3573         }
3574 
3575         public synchronized Map<String, ComputedCssStyleDeclaration> remove(final DomNode element) {
3576             return computedStyles_.remove(element);
3577         }
3578 
3579         private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
3580             in.defaultReadObject();
3581             computedStyles_ = new WeakHashMap<>();
3582         }
3583     }
3584 
3585     private static final class MappedElementIndexEntry implements Serializable {
3586         private final ArrayList<DomElement> elements_;
3587         private boolean sorted_;
3588 
3589         MappedElementIndexEntry() {
3590             // we do not expect to many elements having the same id/name
3591             elements_ = new ArrayList<>(2);
3592             sorted_ = true;
3593         }
3594 
3595         void add(final DomElement element) {
3596             if (elements_.indexOf(element) == -1) {
3597                 elements_.add(element);
3598                 sorted_ = elements_.size() < 2;
3599             }
3600         }
3601 
3602         DomElement first() {
3603             if (elements_.isEmpty()) {
3604                 return null;
3605             }
3606 
3607             if (sorted_) {
3608                 return elements_.get(0);
3609             }
3610 
3611             elements_.sort(DOCUMENT_POSITION_COMPERATOR);
3612             sorted_ = true;
3613 
3614             return elements_.get(0);
3615         }
3616 
3617         List<DomElement> elements() {
3618             if (sorted_) {
3619                 return elements_;
3620             }
3621 
3622             elements_.sort(DOCUMENT_POSITION_COMPERATOR);
3623             sorted_ = true;
3624 
3625             return elements_;
3626         }
3627 
3628         void remove(final DomElement element) {
3629             elements_.remove(element);
3630             sorted_ = elements_.size() < 2;
3631         }
3632     }
3633 }