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;
16  
17  import static java.nio.charset.StandardCharsets.ISO_8859_1;
18  import static java.nio.charset.StandardCharsets.UTF_8;
19  import static org.htmlunit.BrowserVersionFeatures.DATA_URL_MIME_TYPE_STANDARD_SERIALIZATION;
20  
21  import java.io.BufferedInputStream;
22  import java.io.File;
23  import java.io.FileNotFoundException;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.ObjectInputStream;
27  import java.io.Serializable;
28  import java.lang.ref.Cleaner;
29  import java.lang.ref.Cleaner.Cleanable;
30  import java.lang.ref.WeakReference;
31  import java.net.MalformedURLException;
32  import java.net.URL;
33  import java.net.URLConnection;
34  import java.net.URLDecoder;
35  import java.nio.charset.Charset;
36  import java.nio.file.Files;
37  import java.util.ArrayList;
38  import java.util.Collections;
39  import java.util.ConcurrentModificationException;
40  import java.util.Date;
41  import java.util.HashMap;
42  import java.util.HashSet;
43  import java.util.Iterator;
44  import java.util.LinkedHashMap;
45  import java.util.LinkedHashSet;
46  import java.util.List;
47  import java.util.Locale;
48  import java.util.Map;
49  import java.util.Objects;
50  import java.util.Set;
51  import java.util.concurrent.ConcurrentLinkedDeque;
52  import java.util.concurrent.Executor;
53  import java.util.concurrent.ExecutorService;
54  import java.util.concurrent.Executors;
55  import java.util.concurrent.ThreadFactory;
56  import java.util.concurrent.ThreadPoolExecutor;
57  import java.util.function.Predicate;
58  import java.util.function.UnaryOperator;
59  
60  import org.apache.commons.logging.Log;
61  import org.apache.commons.logging.LogFactory;
62  import org.apache.http.NoHttpResponseException;
63  import org.apache.http.client.CredentialsProvider;
64  import org.apache.http.cookie.MalformedCookieException;
65  import org.htmlunit.attachment.Attachment;
66  import org.htmlunit.attachment.AttachmentHandler;
67  import org.htmlunit.csp.Policy;
68  import org.htmlunit.csp.PolicyList;
69  import org.htmlunit.csp.url.URI;
70  import org.htmlunit.css.ComputedCssStyleDeclaration;
71  import org.htmlunit.cssparser.parser.CSSErrorHandler;
72  import org.htmlunit.cssparser.parser.javacc.CSS3Parser;
73  import org.htmlunit.html.BaseFrameElement;
74  import org.htmlunit.html.DomElement;
75  import org.htmlunit.html.DomNode;
76  import org.htmlunit.html.FrameWindow;
77  import org.htmlunit.html.FrameWindow.PageDenied;
78  import org.htmlunit.html.HtmlElement;
79  import org.htmlunit.html.HtmlInlineFrame;
80  import org.htmlunit.html.HtmlPage;
81  import org.htmlunit.html.XHtmlPage;
82  import org.htmlunit.html.csp.ContentSecurityPolicyViolation;
83  import org.htmlunit.html.csp.ContentSecurityPolicyViolationListener;
84  import org.htmlunit.html.parser.HTMLParser;
85  import org.htmlunit.html.parser.HTMLParserListener;
86  import org.htmlunit.http.Cookie;
87  import org.htmlunit.http.HttpStatus;
88  import org.htmlunit.http.HttpUtils;
89  import org.htmlunit.httpclient.HttpClientConverter;
90  import org.htmlunit.javascript.AbstractJavaScriptEngine;
91  import org.htmlunit.javascript.DefaultJavaScriptErrorListener;
92  import org.htmlunit.javascript.HtmlUnitScriptable;
93  import org.htmlunit.javascript.JavaScriptEngine;
94  import org.htmlunit.javascript.JavaScriptErrorListener;
95  import org.htmlunit.javascript.background.JavaScriptJobManager;
96  import org.htmlunit.javascript.host.BroadcastChannel;
97  import org.htmlunit.javascript.host.Location;
98  import org.htmlunit.javascript.host.Window;
99  import org.htmlunit.javascript.host.dom.Node;
100 import org.htmlunit.javascript.host.event.Event;
101 import org.htmlunit.javascript.host.file.Blob;
102 import org.htmlunit.javascript.host.html.HTMLIFrameElement;
103 import org.htmlunit.protocol.data.DataURLConnection;
104 import org.htmlunit.util.HeaderUtils;
105 import org.htmlunit.util.MimeType;
106 import org.htmlunit.util.NameValuePair;
107 import org.htmlunit.util.SerializableLock;
108 import org.htmlunit.util.StringUtils;
109 import org.htmlunit.util.UrlUtils;
110 import org.htmlunit.websocket.JettyWebSocketAdapter.JettyWebSocketAdapterFactory;
111 import org.htmlunit.websocket.WebSocketAdapter;
112 import org.htmlunit.websocket.WebSocketAdapterFactory;
113 import org.htmlunit.websocket.WebSocketListener;
114 import org.htmlunit.webstart.WebStartHandler;
115 
116 /**
117  * The main starting point in HtmlUnit: this class simulates a web browser.
118  * <p>
119  * A standard usage of HtmlUnit will start with using the {@link #getPage(String)} method
120  * (or {@link #getPage(URL)}) to load a first {@link Page}
121  * and will continue with further processing on this page depending on its type.
122  * </p>
123  * <b>Example:</b><br>
124  * <br>
125  * <code>
126  * final WebClient webClient = new WebClient();<br>
127  * final {@link HtmlPage} startPage = webClient.getPage("http://htmlunit.sf.net");<br>
128  * assertEquals("HtmlUnit - Welcome to HtmlUnit", startPage.{@link HtmlPage#getTitleText() getTitleText}());
129  * </code>
130  * <p>
131  * Note: a {@link WebClient} instance is <b>not thread safe</b>. It is intended to be used from a single thread.
132  * </p>
133  * @author Mike Bowler
134  * @author Mike J. Bresnahan
135  * @author Dominique Broeglin
136  * @author Noboru Sinohara
137  * @author Chen Jun
138  * @author David K. Taylor
139  * @author Christian Sell
140  * @author Ben Curren
141  * @author Marc Guillemot
142  * @author Chris Erskine
143  * @author Daniel Gredler
144  * @author Sergey Gorelkin
145  * @author Hans Donner
146  * @author Paul King
147  * @author Ahmed Ashour
148  * @author Bruce Chapman
149  * @author Sudhan Moghe
150  * @author Martin Tamme
151  * @author Amit Manjhi
152  * @author Nicolas Belisle
153  * @author Ronald Brill
154  * @author Frank Danek
155  * @author Joerg Werner
156  * @author Anton Demydenko
157  * @author Sergio Moreno
158  * @author Lai Quang Duong
159  * @author René Schwietzke
160  * @author Sven Strickroth
161  * @author Ashutosh Panda
162  * @author Vidya m
163  */
164 @SuppressWarnings("PMD.TooManyFields")
165 public class WebClient implements Serializable, AutoCloseable {
166 
167     /** Logging support. */
168     private static final Log LOG = LogFactory.getLog(WebClient.class);
169 
170     /** Like the Firefox default value for {@code network.http.redirection-limit}. */
171     private static final int ALLOWED_REDIRECTIONS_SAME_URL = 20;
172     private static final WebResponseData RESPONSE_DATA_NO_HTTP_RESPONSE = new WebResponseData(
173             0, "No HTTP Response", Collections.emptyList());
174 
175     static final Cleaner CLEANER = Cleaner.create();
176 
177     /**
178      * These response headers are not copied from a 304 response to the cached
179      * response headers. This list is based on Chromium http_response_headers.cc
180      */
181     private static final String[] DISCARDING_304_RESPONSE_HEADER_NAMES = {
182         "connection",
183         "proxy-connection",
184         "keep-alive",
185         "www-authenticate",
186         "proxy-authenticate",
187         "proxy-authorization",
188         "te",
189         "trailer",
190         "transfer-encoding",
191         "upgrade",
192         "content-location",
193         "content-md5",
194         "etag",
195         "content-encoding",
196         "content-range",
197         "content-type",
198         "content-length",
199         "x-frame-options",
200         "x-xss-protection",
201     };
202 
203     private static final String[] DISCARDING_304_HEADER_PREFIXES = {
204         "x-content-",
205         "x-webkit-"
206     };
207 
208     private transient WebConnection webConnection_;
209     private CredentialsProvider credentialsProvider_ = new DefaultCredentialsProvider();
210     private CookieManager cookieManager_ = new CookieManager();
211     private WebSocketAdapterFactory webSocketAdapterFactory_;
212     private transient AbstractJavaScriptEngine<?> scriptEngine_;
213     private transient List<LoadJob> loadQueue_;
214     private final Map<String, String> requestHeaders_ = Collections.synchronizedMap(new HashMap<>(89));
215     private IncorrectnessListener incorrectnessListener_ = new IncorrectnessListenerImpl();
216     private WebConsole webConsole_;
217     private transient ExecutorService executor_;
218     /** Guards the lazy creation and the shutdown of the {@link #executor_}. */
219     private final SerializableLock executorLock_ = new SerializableLock();
220 
221     private AlertHandler alertHandler_;
222     private ContentSecurityPolicyViolationListener contentSecurityPolicyViolationListener_;
223     private ConfirmHandler confirmHandler_;
224     private PromptHandler promptHandler_;
225     private StatusHandler statusHandler_;
226     private AttachmentHandler attachmentHandler_;
227     private ClipboardHandler clipboardHandler_;
228     private PrintHandler printHandler_;
229     private WebStartHandler webStartHandler_;
230     private FrameContentHandler frameContentHandler_;
231 
232     private AjaxController ajaxController_ = new AjaxController();
233 
234     private final BrowserVersion browserVersion_;
235     private PageCreator pageCreator_ = new DefaultPageCreator();
236 
237     // we need a separate one to be sure the one is always informed as first
238     // one. Only then we can make sure our state is consistent when the others
239     // are informed.
240     private CurrentWindowTracker currentWindowTracker_;
241     private final Set<WebWindowListener> webWindowListeners_ = new HashSet<>(5);
242 
243     private final List<TopLevelWindow> topLevelWindows_ =
244             Collections.synchronizedList(new ArrayList<>()); // top-level windows
245     private final List<WebWindow> windows_ = Collections.synchronizedList(new ArrayList<>()); // all windows
246     private transient List<WeakReference<JavaScriptJobManager>> jobManagers_ =
247             Collections.synchronizedList(new ArrayList<>());
248     private WebWindow currentWindow_;
249 
250     private transient BlobUrlStore blobUrlStore_ = new BlobUrlStore();
251 
252     private HTMLParserListener htmlParserListener_;
253     private CSSErrorHandler cssErrorHandler_ = new DefaultCssErrorHandler();
254     private OnbeforeunloadHandler onbeforeunloadHandler_;
255     private Cache cache_ = new Cache();
256 
257     // mini pool to save resource when parsing CSS
258     private transient CSS3ParserPool css3ParserPool_ = new CSS3ParserPool();
259 
260     /** target "_blank". */
261     public static final String TARGET_BLANK = "_blank";
262 
263     /** target "_self". */
264     public static final String TARGET_SELF = "_self";
265 
266     /** target "_parent". */
267     private static final String TARGET_PARENT = "_parent";
268     /** target "_top". */
269     private static final String TARGET_TOP = "_top";
270 
271     private ScriptPreProcessor scriptPreProcessor_;
272 
273     private RefreshHandler refreshHandler_ = new NiceRefreshHandler(2);
274     private JavaScriptErrorListener javaScriptErrorListener_ = new DefaultJavaScriptErrorListener();
275 
276     private final WebClientOptions options_ = new WebClientOptions();
277     private final boolean javaScriptEngineEnabled_;
278     private final StorageHolder storageHolder_ = new StorageHolder();
279 
280     private transient Set<BroadcastChannel> broadcastChannel_ = new HashSet<>();
281 
282     /**
283      * Creates a web client instance using the browser version returned by
284      * {@link BrowserVersion#getDefault()}.
285      */
286     public WebClient() {
287         this(BrowserVersion.getDefault());
288     }
289 
290     /**
291      * Creates a web client instance using the specified {@link BrowserVersion}.
292      * @param browserVersion the browser version to simulate
293      */
294     public WebClient(final BrowserVersion browserVersion) {
295         this(browserVersion, null, -1);
296     }
297 
298     /**
299      * Creates an instance that will use the specified {@link BrowserVersion} and proxy server.
300      * @param browserVersion the browser version to simulate
301      * @param proxyHost the server that will act as proxy or null for no proxy
302      * @param proxyPort the port to use on the proxy server
303      */
304     public WebClient(final BrowserVersion browserVersion, final String proxyHost, final int proxyPort) {
305         this(browserVersion, true, proxyHost, proxyPort, null);
306     }
307 
308     /**
309      * Creates an instance that will use the specified {@link BrowserVersion} and proxy server.
310      * @param browserVersion the browser version to simulate
311      * @param proxyHost the server that will act as proxy or null for no proxy
312      * @param proxyPort the port to use on the proxy server
313      * @param proxyScheme the scheme http/https
314      */
315     public WebClient(final BrowserVersion browserVersion,
316             final String proxyHost, final int proxyPort, final String proxyScheme) {
317         this(browserVersion, true, proxyHost, proxyPort, proxyScheme);
318     }
319 
320     /**
321      * Creates an instance that will use the specified {@link BrowserVersion} and proxy server.
322      * @param browserVersion the browser version to simulate
323      * @param javaScriptEngineEnabled set to false if the simulated browser should not support javaScript
324      * @param proxyHost the server that will act as proxy or null for no proxy
325      * @param proxyPort the port to use on the proxy server
326      */
327     public WebClient(final BrowserVersion browserVersion, final boolean javaScriptEngineEnabled,
328             final String proxyHost, final int proxyPort) {
329         this(browserVersion, javaScriptEngineEnabled, proxyHost, proxyPort, null);
330     }
331 
332     /**
333      * Creates an instance that will use the specified {@link BrowserVersion} and proxy server.
334      * @param browserVersion the browser version to simulate
335      * @param javaScriptEngineEnabled set to false if the simulated browser should not support javaScript
336      * @param proxyHost the server that will act as proxy or null for no proxy
337      * @param proxyPort the port to use on the proxy server
338      * @param proxyScheme the scheme http/https
339      */
340     public WebClient(final BrowserVersion browserVersion, final boolean javaScriptEngineEnabled,
341             final String proxyHost, final int proxyPort, final String proxyScheme) {
342         WebAssert.notNull("browserVersion", browserVersion);
343 
344         browserVersion_ = browserVersion;
345         javaScriptEngineEnabled_ = javaScriptEngineEnabled;
346 
347         if (proxyHost == null) {
348             getOptions().setProxyConfig(new ProxyConfig());
349         }
350         else {
351             getOptions().setProxyConfig(new ProxyConfig(proxyHost, proxyPort, proxyScheme));
352         }
353 
354         webConnection_ = new HttpWebConnection(this); // this has to be done after the browser version was set
355         if (javaScriptEngineEnabled_) {
356             scriptEngine_ = new JavaScriptEngine(this);
357         }
358         loadQueue_ = new ArrayList<>();
359 
360         webSocketAdapterFactory_ = new JettyWebSocketAdapterFactory();
361 
362         // The window must be constructed AFTER the script engine.
363         currentWindowTracker_ = new CurrentWindowTracker(this, true);
364         currentWindow_ = new TopLevelWindow("", this);
365     }
366 
367     /**
368      * Our simple impl of a ThreadFactory (decorator) to be able to name
369      * our threads.
370      */
371     private static final class ThreadNamingFactory implements ThreadFactory {
372         private static int ID_ = 1;
373         private final ThreadFactory baseFactory_;
374 
375         ThreadNamingFactory(final ThreadFactory aBaseFactory) {
376             baseFactory_ = aBaseFactory;
377         }
378 
379         @Override
380         public Thread newThread(final Runnable aRunnable) {
381             final Thread thread = baseFactory_.newThread(aRunnable);
382             thread.setName("WebClient Thread " + ID_++);
383             return thread;
384         }
385     }
386 
387     /**
388      * Returns the object that will resolve all URL requests.
389      *
390      * @return the connection that will be used
391      */
392     public WebConnection getWebConnection() {
393         return webConnection_;
394     }
395 
396     /**
397      * Sets the object that will resolve all URL requests.
398      *
399      * @param webConnection the new web connection
400      */
401     public void setWebConnection(final WebConnection webConnection) {
402         WebAssert.notNull("webConnection", webConnection);
403         webConnection_ = webConnection;
404     }
405 
406     /**
407      * Send a request to a server and return a Page that represents the
408      * response from the server. This page will be used to populate the provided window.
409      * <p>
410      * The returned {@link Page} will be created by the {@link PageCreator}
411      * configured by {@link #setPageCreator(PageCreator)}, if any.
412      * </p>
413      * <p>
414      * The {@link DefaultPageCreator} will create a {@link Page} depending on the content type of the HTTP response,
415      * basically {@link HtmlPage} for HTML content, {@link org.htmlunit.xml.XmlPage} for XML content,
416      * {@link TextPage} for other text content and {@link UnexpectedPage} for anything else.
417      * </p>
418      *
419      * @param webWindow the WebWindow to load the result of the request into
420      * @param webRequest the web request
421      * @param <P> the page type
422      * @return the page returned by the server when the specified request was made in the specified window
423      * @throws IOException if an IO error occurs
424      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
425      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
426      *
427      * @see WebRequest
428      */
429     public <P extends Page> P getPage(final WebWindow webWindow, final WebRequest webRequest)
430             throws IOException, FailingHttpStatusCodeException {
431         return getPage(webWindow, webRequest, true);
432     }
433 
434     /**
435      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
436      *
437      * Send a request to a server and return a Page that represents the
438      * response from the server. This page will be used to populate the provided window.
439      * <p>
440      * The returned {@link Page} will be created by the {@link PageCreator}
441      * configured by {@link #setPageCreator(PageCreator)}, if any.
442      * </p>
443      * <p>
444      * The {@link DefaultPageCreator} will create a {@link Page} depending on the content type of the HTTP response,
445      * basically {@link HtmlPage} for HTML content, {@link org.htmlunit.xml.XmlPage} for XML content,
446      * {@link TextPage} for other text content and {@link UnexpectedPage} for anything else.
447      * </p>
448      *
449      * @param webWindow the WebWindow to load the result of the request into
450      * @param webRequest the web request
451      * @param addToHistory true if the page should be part of the history
452      * @param <P> the page type
453      * @return the page returned by the server when the specified request was made in the specified window
454      * @throws IOException if an IO error occurs
455      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
456      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
457      *
458      * @see WebRequest
459      */
460     @SuppressWarnings("unchecked")
461     <P extends Page> P getPage(final WebWindow webWindow, final WebRequest webRequest,
462             final boolean addToHistory)
463         throws IOException, FailingHttpStatusCodeException {
464 
465         final Page page = webWindow.getEnclosedPage();
466 
467         if (page != null) {
468             final URL prev = page.getUrl();
469             final URL current = webRequest.getUrl();
470             if (UrlUtils.sameFile(current, prev)
471                         && current.getRef() != null
472                         && !Objects.equals(current.getRef(), prev.getRef())) {
473                 // We're just navigating to an anchor within the current page.
474                 page.getWebResponse().getWebRequest().setUrl(current);
475                 if (addToHistory) {
476                     webWindow.getHistory().addPage(page);
477                 }
478 
479                 // clear the cache because the anchors are now matched by
480                 // the target pseudo style
481                 if (page instanceof HtmlPage htmlPage) {
482                     htmlPage.clearComputedStyles();
483                 }
484 
485                 final Window window = webWindow.getScriptableObject();
486                 if (window != null) { // js enabled
487                     window.getLocation().setHash(current.getRef());
488                 }
489                 return (P) page;
490             }
491 
492             if (page.isHtmlPage()) {
493                 final HtmlPage htmlPage = (HtmlPage) page;
494                 if (!htmlPage.isOnbeforeunloadAccepted()) {
495                     LOG.debug("The registered OnbeforeunloadHandler rejected to load a new page.");
496                     return (P) page;
497                 }
498             }
499         }
500 
501         if (LOG.isDebugEnabled()) {
502             LOG.debug("Get page for window named '" + webWindow.getName() + "', using " + webRequest);
503         }
504 
505         WebResponse webResponse;
506         final String protocol = webRequest.getUrl().getProtocol();
507         if ("javascript".equals(protocol)) {
508             webResponse = makeWebResponseForJavaScriptUrl(webWindow, webRequest.getUrl(), webRequest.getCharset());
509             if (webWindow.getEnclosedPage() != null && webWindow.getEnclosedPage().getWebResponse() == webResponse) {
510                 // a javascript:... url with result of type undefined didn't changed the page
511                 return (P) webWindow.getEnclosedPage();
512             }
513         }
514         else {
515             // the document of an iframe with srcdoc attribute is not fetched (the content is the attribute)
516             webResponse = makeWebResponseForSrcdoc(webWindow, webRequest);
517             try {
518                 if (webResponse == null) {
519                     webResponse = loadWebResponse(webRequest);
520                 }
521             }
522             catch (final NoHttpResponseException e) {
523                 webResponse = new WebResponse(RESPONSE_DATA_NO_HTTP_RESPONSE, webRequest, 0);
524             }
525 
526             if (webResponse == null) {
527                 // blocked by the redirect filter of the request; the window content is not changed
528                 return (P) webWindow.getEnclosedPage();
529             }
530         }
531 
532         printContentIfNecessary(webResponse);
533         loadWebResponseInto(webResponse, webWindow);
534 
535         // start execution here
536         // note: we have to do this also if the server reports an error!
537         //       e.g. if the server returns a 404 error page that includes javascript
538         if (scriptEngine_ != null) {
539             scriptEngine_.registerWindowAndMaybeStartEventLoop(webWindow);
540         }
541 
542         // check and report problems if needed
543         throwFailingHttpStatusCodeExceptionIfNecessary(webResponse);
544         return (P) webWindow.getEnclosedPage();
545     }
546 
547     /**
548      * Convenient method to build a URL and load it into the current WebWindow as it would be done
549      * by {@link #getPage(WebWindow, WebRequest)}.
550      * @param url the URL of the new content; in contrast to real browsers plain file url's are not supported.
551      *        You have to use the 'file', 'data', 'blob', 'http' or 'https' protocol.
552      * @param <P> the page type
553      * @return the new page
554      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
555      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true.
556      * @throws IOException if an IO problem occurs
557      * @throws MalformedURLException if no URL can be created from the provided string
558      */
559     public <P extends Page> P getPage(final String url) throws IOException, FailingHttpStatusCodeException,
560         MalformedURLException {
561         return getPage(UrlUtils.toUrlUnsafe(url));
562     }
563 
564     /**
565      * Convenient method to load a URL into the current top WebWindow as it would be done
566      * by {@link #getPage(WebWindow, WebRequest)}.
567      * @param url the URL of the new content; in contrast to real browsers plain file url's are not supported.
568      *        You have to use the 'file', 'data', 'blob', 'http' or 'https' protocol.
569      * @param <P> the page type
570      * @return the new page
571      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
572      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true.
573      * @throws IOException if an IO problem occurs
574      */
575     public <P extends Page> P getPage(final URL url) throws IOException, FailingHttpStatusCodeException {
576         final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
577                                                           getBrowserVersion().getAcceptEncodingHeader());
578         request.setCharset(UTF_8);
579         return getPage(getCurrentWindow().getTopWindow(), request);
580     }
581 
582     /**
583      * Convenient method to load a web request into the current top WebWindow.
584      * @param request the request parameters
585      * @param <P> the page type
586      * @return the new page
587      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
588      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true.
589      * @throws IOException if an IO problem occurs
590      * @see #getPage(WebWindow,WebRequest)
591      */
592     public <P extends Page> P getPage(final WebRequest request) throws IOException,
593         FailingHttpStatusCodeException {
594         return getPage(getCurrentWindow().getTopWindow(), request);
595     }
596 
597     /**
598      * <p>Creates a page based on the specified response and inserts it into the specified window. All page
599      * initialization and event notification is handled here.</p>
600      *
601      * <p>Note that if the page created is an attachment page, and an {@link AttachmentHandler} has been
602      * registered with this client, the page is <b>not</b> loaded into the specified window; in this case,
603      * the page is loaded into a new window, and attachment handling is delegated to the registered
604      * <code>AttachmentHandler</code>.</p>
605      *
606      * @param webResponse the response that will be used to create the new page
607      * @param webWindow the window that the new page will be placed within
608      * @throws IOException if an IO error occurs
609      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
610      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
611      * @return the newly created page
612      * @see #setAttachmentHandler(AttachmentHandler)
613      */
614     public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow)
615         throws IOException, FailingHttpStatusCodeException {
616         return loadWebResponseInto(webResponse, webWindow, null);
617     }
618 
619     /**
620      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
621      *
622      * <p>Creates a page based on the specified response and inserts it into the specified window. All page
623      * initialization and event notification is handled here.</p>
624      *
625      * <p>Note that if the page created is an attachment page, and an {@link AttachmentHandler} has been
626      * registered with this client, the page is <b>not</b> loaded into the specified window; in this case,
627      * the page is loaded into a new window, and attachment handling is delegated to the registered
628      * <code>AttachmentHandler</code>.</p>
629      *
630      * @param webResponse the response that will be used to create the new page
631      * @param webWindow the window that the new page will be placed within
632      * @param forceAttachmentWithFilename if not {@code null}, handle this as an attachment with the specified name
633      *        or if an empty string ("") use the filename provided in the response
634      * @throws IOException if an IO error occurs
635      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
636      *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
637      * @return the newly created page
638      * @see #setAttachmentHandler(AttachmentHandler)
639      */
640     public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow,
641             final String forceAttachmentWithFilename)
642             throws IOException, FailingHttpStatusCodeException {
643         return loadWebResponseInto(webResponse, webWindow, forceAttachmentWithFilename, null);
644     }
645 
646     /**
647      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
648      *
649      * Loads about:blank into the given frame window and marks the content as denied
650      * (e.g. if the url of the frame is blocked by the frame-src directive of the
651      * Content-Security-Policy). Like for a page denied by frame-ancestors or X-Frame-Options,
652      * the content of the frame is not accessible and the load event is fired.
653      *
654      * @param frameWindow the frame window
655      * @param pageDenied the reason the page is denied
656      * @throws IOException if an IO error occurs
657      */
658     public void loadDeniedPageInto(final FrameWindow frameWindow, final PageDenied pageDenied)
659             throws IOException {
660         final WebResponse aboutBlank = loadWebResponse(WebRequest.newAboutBlankRequest());
661         loadWebResponseInto(aboutBlank, frameWindow, null, pageDenied);
662         if (scriptEngine_ != null) {
663             scriptEngine_.registerWindowAndMaybeStartEventLoop(frameWindow);
664         }
665     }
666 
667     private Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow,
668             final String forceAttachmentWithFilename, final PageDenied forcedPageDenied)
669             throws IOException, FailingHttpStatusCodeException {
670         WebAssert.notNull("webResponse", webResponse);
671         WebAssert.notNull("webWindow", webWindow);
672 
673         if (webResponse.getStatusCode() == HttpStatus.NO_CONTENT_204) {
674             return webWindow.getEnclosedPage();
675         }
676 
677         if (webStartHandler_ != null && "application/x-java-jnlp-file".equals(webResponse.getContentType())) {
678             webStartHandler_.handleJnlpResponse(webResponse);
679             return webWindow.getEnclosedPage();
680         }
681 
682         if (attachmentHandler_ != null
683                 && (forceAttachmentWithFilename != null || attachmentHandler_.isAttachment(webResponse))) {
684 
685             // check content disposition header for nothing provided
686             String filename = forceAttachmentWithFilename;
687             if (StringUtils.isEmptyOrNull(filename)) {
688                 filename = Attachment.getSuggestedFilenameFrom(webResponse.getContentDisposition());
689             }
690             if (StringUtils.isEmptyOrNull(filename)) {
691                 filename = null;
692             }
693 
694             if (attachmentHandler_.handleAttachment(webResponse, filename)) {
695                 // the handling is done by the attachment handler;
696                 // do not open a new window
697                 return webWindow.getEnclosedPage();
698             }
699 
700             final WebWindow w = openWindow(null, null, webWindow);
701             final Page page = pageCreator_.createPage(webResponse, w);
702             attachmentHandler_.handleAttachment(page, filename);
703             return page;
704         }
705 
706         final Page oldPage = webWindow.getEnclosedPage();
707         if (oldPage != null) {
708             // Remove the old page before create new one.
709             oldPage.cleanUp();
710         }
711 
712         Page newPage = null;
713         FrameWindow.PageDenied pageDenied = PageDenied.NONE;
714         if (windows_.contains(webWindow)) {
715             if (forcedPageDenied != null) {
716                 pageDenied = forcedPageDenied;
717             }
718             else if (webWindow instanceof FrameWindow window) {
719                 pageDenied = getPageDenied(webResponse, window);
720             }
721 
722             if (pageDenied == PageDenied.NONE) {
723                 newPage = pageCreator_.createPage(webResponse, webWindow);
724             }
725             else {
726                 try {
727                     final WebResponse aboutBlank = loadWebResponse(WebRequest.newAboutBlankRequest());
728                     newPage = pageCreator_.createPage(aboutBlank, webWindow);
729                     // TODO - maybe we have to attach to original request/response to the page
730 
731                     ((FrameWindow) webWindow).setPageDenied(pageDenied);
732                 }
733                 catch (final IOException ignored) {
734                     // ignore
735                 }
736             }
737 
738             if (windows_.contains(webWindow)) {
739                 fireWindowContentChanged(new WebWindowEvent(webWindow, WebWindowEvent.CHANGE, oldPage, newPage));
740 
741                 // The page being loaded may already have been replaced by another page via JavaScript code.
742                 if (webWindow.getEnclosedPage() == newPage) {
743                     newPage.initialize();
744                     // hack: onload should be fired the same way for all type of pages
745                     // here is a hack to handle non HTML pages
746                     if (isJavaScriptEnabled()
747                             && webWindow instanceof FrameWindow fw && !newPage.isHtmlPage()) {
748                         final BaseFrameElement frame = fw.getFrameElement();
749                         if (frame.hasEventHandlers("onload")) {
750                             if (LOG.isDebugEnabled()) {
751                                 LOG.debug("Executing onload handler for " + frame);
752                             }
753                             final Event event = new Event(frame, Event.TYPE_LOAD);
754                             ((Node) frame.getScriptableObject()).executeEventLocally(event);
755                         }
756                     }
757                 }
758             }
759         }
760         return newPage;
761     }
762 
763     /**
764      * Checks if the given response is allowed to be shown in the given frame window.
765      * Like in the browsers
766      * <ul>
767      *   <li>the frame-ancestors directives of all Content-Security-Policy headers
768      *       (each header may contain a comma separated list of policies) have to allow
769      *       all ancestors of the frame (up to the top window)</li>
770      *   <li>the X-Frame-Options header is ignored if one of the policies contains
771      *       a frame-ancestors directive</li>
772      *   <li>X-Frame-Options SAMEORIGIN requires all ancestors to be same origin
773      *       with the response; unknown values (e.g. ALLOW-FROM) are ignored</li>
774      * </ul>
775      *
776      * @param webResponse the response to check
777      * @param window the frame window the response should be loaded into
778      * @return the reason the page is denied or {@link PageDenied#NONE}
779      * @throws MalformedURLException if an URL is invalid
780      */
781     private static PageDenied getPageDenied(final WebResponse webResponse, final FrameWindow window)
782             throws MalformedURLException {
783         final URL url = webResponse.getWebRequest().getUrl();
784 
785         final List<Policy> policies = new ArrayList<>();
786         final Set<String> xFrameOptions = new LinkedHashSet<>();
787         for (final NameValuePair header : webResponse.getResponseHeaders()) {
788             final String value = header.getValue();
789             if (StringUtils.isBlank(value)) {
790                 continue;
791             }
792 
793             if (HttpHeader.CONTENT_SECURIRY_POLICY.equalsIgnoreCase(header.getName())) {
794                 policies.addAll(Policy.parseSerializedCSPList(value,
795                         Policy.PolicyListErrorConsumer.ignored).getPolicies());
796             }
797             else if (HttpHeader.X_FRAME_OPTIONS.equalsIgnoreCase(header.getName())) {
798                 for (final String option : value.split(",")) {
799                     final String trimmed = option.trim().toLowerCase(Locale.ROOT);
800                     if (!trimmed.isEmpty()) {
801                         xFrameOptions.add(trimmed);
802                     }
803                 }
804             }
805         }
806 
807         final List<URL> ancestors = getFrameAncestorUrls(window);
808 
809         boolean hasFrameAncestors = false;
810         for (final Policy policy : policies) {
811             if (policy.frameAncestors().isPresent()) {
812                 hasFrameAncestors = true;
813                 break;
814             }
815         }
816 
817         if (hasFrameAncestors) {
818             final String origin = UrlUtils.getUrlWithoutPathRefQuery(url).toExternalForm();
819             final PolicyList policyList = new PolicyList(policies);
820             for (final URL ancestor : ancestors) {
821                 final String ancestorOrigin = UrlUtils.getUrlWithoutPathRefQuery(ancestor).toExternalForm();
822                 if (!policyList.allowsFrameAncestor(URI.parseURI(ancestorOrigin), URI.parseURI(origin))) {
823                     if (LOG.isWarnEnabled()) {
824                         LOG.warn("Load denied by Content-Security-Policy: '" + policyList + "' - '"
825                                 + url + "' does not permit framing by '" + ancestorOrigin + "'.");
826                     }
827 
828                     final ContentSecurityPolicyViolationListener listener =
829                             window.getWebClient().getContentSecurityPolicyViolationListener();
830                     if (listener != null) {
831                         final ContentSecurityPolicyViolation violation = new ContentSecurityPolicyViolation(
832                                 url.toExternalForm(), ancestorOrigin, "frame-ancestors", policyList.toString(),
833                                 "", "", 0, 0, webResponse.getStatusCode(), false);
834                         listener.violation(window.getEnclosingPage(), violation);
835                     }
836                     return PageDenied.BY_CONTENT_SECURIRY_POLICY;
837                 }
838             }
839 
840             // X-Frame-Options is ignored if there is a frame-ancestors directive
841             return PageDenied.NONE;
842         }
843 
844         if (xFrameOptions.isEmpty()) {
845             return PageDenied.NONE;
846         }
847 
848         if (xFrameOptions.size() > 1) {
849             // conflicting values
850             if (xFrameOptions.contains("deny")
851                     || xFrameOptions.contains("sameorigin")
852                     || xFrameOptions.contains("allowall")) {
853                 return logXFrameOptionsDenied(url, xFrameOptions);
854             }
855             return PageDenied.NONE;
856         }
857 
858         final String xFrameOption = xFrameOptions.iterator().next();
859         if ("deny".equals(xFrameOption)) {
860             return logXFrameOptionsDenied(url, xFrameOptions);
861         }
862         if ("sameorigin".equals(xFrameOption)) {
863             for (final URL ancestor : ancestors) {
864                 if (!UrlUtils.isSameOrigin(ancestor, url)) {
865                     return logXFrameOptionsDenied(url, xFrameOptions);
866                 }
867             }
868         }
869         return PageDenied.NONE;
870     }
871 
872     private static PageDenied logXFrameOptionsDenied(final URL url, final Set<String> xFrameOptions) {
873         if (LOG.isWarnEnabled()) {
874             LOG.warn("Load denied by X-Frame-Options: " + xFrameOptions + " - '"
875                     + url + "' does not permit framing.");
876         }
877         return PageDenied.BY_X_FRAME_OPTIONS;
878     }
879 
880     /**
881      * Returns the urls of all ancestors of the given frame window (starting with the
882      * page containing the frame up to the page of the top window) used as origin when
883      * checking the frame-ancestors directive or the X-Frame-Options header.
884      *
885      * @param window the frame window
886      * @return the urls
887      */
888     private static List<URL> getFrameAncestorUrls(final FrameWindow window) {
889         final List<URL> urls = new ArrayList<>();
890         WebWindow current = window;
891         while (current instanceof FrameWindow frameWindow) {
892             final Page page = frameWindow.getEnclosingPage();
893             urls.add(getFrameAncestorUrl(page));
894             current = page.getEnclosingWindow();
895         }
896         return urls;
897     }
898 
899     /**
900      * Returns the url of the given page used as origin when checking the frame-ancestors
901      * directive of a content security policy. Like in the browsers, an about:blank (or about:srcdoc)
902      * frame inherits the origin of its parent.
903      *
904      * @param page the page containing the frame
905      * @return the url
906      */
907     private static URL getFrameAncestorUrl(final Page page) {
908         Page current = page;
909         URL url = current.getUrl();
910         while ((UrlUtils.ABOUT_BLANK.equals(url.toExternalForm())
911                     || UrlUtils.ABOUT_SRCDOC.equals(url.toExternalForm()))
912                 && current.getEnclosingWindow() instanceof FrameWindow frameWindow) {
913             current = frameWindow.getEnclosingPage();
914             url = current.getUrl();
915         }
916         return url;
917     }
918 
919     /**
920      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
921      *
922      * <p>Logs the response's content if its status code indicates a request failure and
923      * {@link WebClientOptions#isPrintContentOnFailingStatusCode()} returns {@code true}.
924      * </p>
925      *
926      * @param webResponse the response whose content may be logged
927      */
928     public void printContentIfNecessary(final WebResponse webResponse) {
929         if (getOptions().isPrintContentOnFailingStatusCode()
930                 && !webResponse.isSuccess() && LOG.isInfoEnabled()) {
931             final String contentType = webResponse.getContentType();
932             LOG.info("statusCode=[" + webResponse.getStatusCode() + "] contentType=[" + contentType + "]");
933             LOG.info(webResponse.getContentAsString());
934         }
935     }
936 
937     /**
938      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
939      *
940      * <p>Throws a {@link FailingHttpStatusCodeException} if the request's status code indicates a request
941      * failure and {@link WebClientOptions#isThrowExceptionOnFailingStatusCode()} returns {@code true}.
942      * </p>
943      *
944      * @param webResponse the response which may trigger a {@link FailingHttpStatusCodeException}
945      */
946     public void throwFailingHttpStatusCodeExceptionIfNecessary(final WebResponse webResponse) {
947         if (getOptions().isThrowExceptionOnFailingStatusCode() && !webResponse.isSuccessOrUseProxyOrNotModified()) {
948             throw new FailingHttpStatusCodeException(webResponse);
949         }
950     }
951 
952     /**
953      * Adds a header which will be sent with EVERY request from this client.
954      * This list is empty per default; use this to add specific headers for your
955      * case.
956      * @param name the name of the header to add
957      * @param value the value of the header to add
958      * @see #removeRequestHeader(String)
959      */
960     public void addRequestHeader(final String name, final String value) {
961         if (HttpHeader.COOKIE_LC.equalsIgnoreCase(name)) {
962             throw new IllegalArgumentException("Do not add 'Cookie' header, use .getCookieManager() instead");
963         }
964         requestHeaders_.put(name, value);
965     }
966 
967     /**
968      * Removes a header from being sent with EVERY request from this client.
969      * This list is empty per default; use this method to remove specific headers
970      * your have added using {{@link #addRequestHeader(String, String)} before.<br>
971      * You can't use this to avoid sending standard headers like "Accept-Language"
972      * or "Sec-Fetch-Dest".
973      * @param name the name of the header to remove
974      * @see #addRequestHeader
975      */
976     public void removeRequestHeader(final String name) {
977         requestHeaders_.remove(name);
978     }
979 
980     /**
981      * Sets the credentials provider that will provide authentication information when
982      * trying to access protected information on a web server. This information is
983      * required when the server is using Basic HTTP authentication, NTLM authentication,
984      * or Digest authentication.
985      * @param credentialsProvider the new credentials provider to use to authenticate
986      */
987     public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
988         WebAssert.notNull("credentialsProvider", credentialsProvider);
989         credentialsProvider_ = credentialsProvider;
990     }
991 
992     /**
993      * Returns the credentials provider for this client instance. By default, this
994      * method returns an instance of {@link DefaultCredentialsProvider}.
995      * @return the credentials provider for this client instance
996      */
997     public CredentialsProvider getCredentialsProvider() {
998         return credentialsProvider_;
999     }
1000 
1001     /**
1002      * This method is intended for testing only - use at your own risk.
1003      * @return the current JavaScript engine (never {@code null})
1004      */
1005     public AbstractJavaScriptEngine<?> getJavaScriptEngine() {
1006         return scriptEngine_;
1007     }
1008 
1009     /**
1010      * This method is intended for testing only - use at your own risk.
1011      *
1012      * @param engine the new script engine to use
1013      */
1014     public void setJavaScriptEngine(final AbstractJavaScriptEngine<?> engine) {
1015         if (engine == null) {
1016             throw new IllegalArgumentException("Can't set JavaScriptEngine to null");
1017         }
1018         scriptEngine_ = engine;
1019     }
1020 
1021     /**
1022      * Returns the cookie manager used by this web client.
1023      * @return the cookie manager used by this web client
1024      */
1025     public CookieManager getCookieManager() {
1026         return cookieManager_;
1027     }
1028 
1029     /**
1030      * Sets the cookie manager used by this web client.
1031      * @param cookieManager the cookie manager used by this web client
1032      */
1033     public void setCookieManager(final CookieManager cookieManager) {
1034         WebAssert.notNull("cookieManager", cookieManager);
1035         cookieManager_ = cookieManager;
1036     }
1037 
1038     /**
1039      * Sets the alert handler for this webclient.
1040      * @param alertHandler the new alerthandler or null if none is specified
1041      */
1042     public void setAlertHandler(final AlertHandler alertHandler) {
1043         alertHandler_ = alertHandler;
1044     }
1045 
1046     /**
1047      * Returns the alert handler for this webclient.
1048      * @return the alert handler or null if one hasn't been set
1049      */
1050     public AlertHandler getAlertHandler() {
1051         return alertHandler_;
1052     }
1053 
1054     /**
1055      * Sets the listener informed about violations of the Content-Security-Policy of the pages.
1056      * @param listener the new listener or null if none is specified
1057      * @see ContentSecurityPolicyViolationListener
1058      */
1059     public void setContentSecurityPolicyViolationListener(final ContentSecurityPolicyViolationListener listener) {
1060         contentSecurityPolicyViolationListener_ = listener;
1061     }
1062 
1063     /**
1064      * Returns the listener informed about violations of the Content-Security-Policy of the pages.
1065      * @return the listener or null if one hasn't been set
1066      */
1067     public ContentSecurityPolicyViolationListener getContentSecurityPolicyViolationListener() {
1068         return contentSecurityPolicyViolationListener_;
1069     }
1070 
1071     /**
1072      * Sets the handler that will be executed when the JavaScript method Window.confirm() is called.
1073      * @param handler the new handler or null if no handler is to be used
1074      */
1075     public void setConfirmHandler(final ConfirmHandler handler) {
1076         confirmHandler_ = handler;
1077     }
1078 
1079     /**
1080      * Returns the confirm handler.
1081      * @return the confirm handler or null if one hasn't been set
1082      */
1083     public ConfirmHandler getConfirmHandler() {
1084         return confirmHandler_;
1085     }
1086 
1087     /**
1088      * Sets the handler that will be executed when the JavaScript method Window.prompt() is called.
1089      * @param handler the new handler or null if no handler is to be used
1090      */
1091     public void setPromptHandler(final PromptHandler handler) {
1092         promptHandler_ = handler;
1093     }
1094 
1095     /**
1096      * Returns the prompt handler.
1097      * @return the prompt handler or null if one hasn't been set
1098      */
1099     public PromptHandler getPromptHandler() {
1100         return promptHandler_;
1101     }
1102 
1103     /**
1104      * Sets the status handler for this webclient.
1105      * @param statusHandler the new status handler or null if none is specified
1106      */
1107     public void setStatusHandler(final StatusHandler statusHandler) {
1108         statusHandler_ = statusHandler;
1109     }
1110 
1111     /**
1112      * Returns the status handler for this {@link WebClient}.
1113      * @return the status handler or null if one hasn't been set
1114      */
1115     public StatusHandler getStatusHandler() {
1116         return statusHandler_;
1117     }
1118 
1119     /**
1120      * Returns the executor for this {@link WebClient}.
1121      * @return the executor
1122      */
1123     public Executor getExecutor() {
1124         synchronized (executorLock_) {
1125             if (executor_ == null) {
1126                 final ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
1127                 threadPoolExecutor.setThreadFactory(new ThreadNamingFactory(threadPoolExecutor.getThreadFactory()));
1128                 // threadPoolExecutor.prestartAllCoreThreads();
1129                 executor_ = threadPoolExecutor;
1130             }
1131 
1132             return executor_;
1133         }
1134     }
1135 
1136     /**
1137      * Changes the ExecutorService for this {@link WebClient}.
1138      * You have to call this before the first use of the executor, otherwise
1139      * an IllegalStateExceptions is thrown.
1140      * @param executor the new Executor.
1141      */
1142     public void setExecutor(final ExecutorService executor) {
1143         synchronized (executorLock_) {
1144             if (executor_ != null) {
1145                 throw new IllegalStateException("Can't change the executor after first use.");
1146             }
1147 
1148             executor_ = executor;
1149         }
1150     }
1151 
1152     /**
1153      * Sets the javascript error listener for this {@link WebClient}.
1154      * When setting to null, the {@link DefaultJavaScriptErrorListener} is used.
1155      * @param javaScriptErrorListener the new JavaScriptErrorListener or null if none is specified
1156      */
1157     public void setJavaScriptErrorListener(final JavaScriptErrorListener javaScriptErrorListener) {
1158         if (javaScriptErrorListener == null) {
1159             javaScriptErrorListener_ = new DefaultJavaScriptErrorListener();
1160         }
1161         else {
1162             javaScriptErrorListener_ = javaScriptErrorListener;
1163         }
1164     }
1165 
1166     /**
1167      * Returns the javascript error listener for this {@link WebClient}.
1168      * @return the javascript error listener or null if one hasn't been set
1169      */
1170     public JavaScriptErrorListener getJavaScriptErrorListener() {
1171         return javaScriptErrorListener_;
1172     }
1173 
1174     /**
1175      * Returns the current browser version.
1176      * @return the current browser version
1177      */
1178     public BrowserVersion getBrowserVersion() {
1179         return browserVersion_;
1180     }
1181 
1182     /**
1183      * Returns the "current" window for this client. This window (or its top window) will be used
1184      * when <code>getPage(...)</code> is called without specifying a window.
1185      * @return the "current" window for this client
1186      */
1187     public WebWindow getCurrentWindow() {
1188         return currentWindow_;
1189     }
1190 
1191     /**
1192      * Sets the "current" window for this client. This is the window that will be used when
1193      * <code>getPage(...)</code> is called without specifying a window.
1194      * @param window the new "current" window for this client
1195      */
1196     public void setCurrentWindow(final WebWindow window) {
1197         WebAssert.notNull("window", window);
1198         if (currentWindow_ == window) {
1199             return;
1200         }
1201         // onBlur event is triggered for focused element of old current window
1202         if (currentWindow_ != null && !currentWindow_.isClosed()) {
1203             final Page enclosedPage = currentWindow_.getEnclosedPage();
1204             if (enclosedPage != null && enclosedPage.isHtmlPage()) {
1205                 final DomElement focusedElement = ((HtmlPage) enclosedPage).getFocusedElement();
1206                 if (focusedElement != null) {
1207                     focusedElement.fireEvent(Event.TYPE_BLUR);
1208                 }
1209             }
1210         }
1211         currentWindow_ = window;
1212 
1213         // when marking an iframe window as current we have no need to move the focus
1214         final boolean isIFrame = currentWindow_ instanceof FrameWindow fw
1215                 && fw.getFrameElement() instanceof HtmlInlineFrame;
1216         if (!isIFrame) {
1217             //1. activeElement becomes focused element for new current window
1218             //2. onFocus event is triggered for focusedElement of new current window
1219             final Page enclosedPage = currentWindow_.getEnclosedPage();
1220             if (enclosedPage != null && enclosedPage.isHtmlPage()) {
1221                 final HtmlPage enclosedHtmlPage = (HtmlPage) enclosedPage;
1222                 final HtmlElement activeElement = enclosedHtmlPage.getActiveElement();
1223                 if (activeElement != null) {
1224                     enclosedHtmlPage.setFocusedElement(activeElement, true);
1225                 }
1226             }
1227         }
1228     }
1229 
1230     /**
1231      * Returns the blob URL store for this client.
1232      * @return the {@link BlobUrlStore} for this client
1233      */
1234     public BlobUrlStore getBlobUrlStore() {
1235         return blobUrlStore_;
1236     }
1237 
1238     /**
1239      * Adds a listener for {@link WebWindowEvent}s. All events from all windows associated with this
1240      * client will be sent to the specified listener.
1241      * @param listener a listener
1242      */
1243     public void addWebWindowListener(final WebWindowListener listener) {
1244         WebAssert.notNull("listener", listener);
1245         webWindowListeners_.add(listener);
1246     }
1247 
1248     /**
1249      * Removes a listener for {@link WebWindowEvent}s.
1250      * @param listener a listener
1251      */
1252     public void removeWebWindowListener(final WebWindowListener listener) {
1253         WebAssert.notNull("listener", listener);
1254         webWindowListeners_.remove(listener);
1255     }
1256 
1257     private void fireWindowContentChanged(final WebWindowEvent event) {
1258         if (currentWindowTracker_ != null) {
1259             currentWindowTracker_.webWindowContentChanged(event);
1260         }
1261         for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1262             listener.webWindowContentChanged(event);
1263         }
1264 
1265         blobUrlStore_.removeForPage(event.getOldPage());
1266     }
1267 
1268     private void fireWindowOpened(final WebWindowEvent event) {
1269         if (currentWindowTracker_ != null) {
1270             currentWindowTracker_.webWindowOpened(event);
1271         }
1272         for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1273             listener.webWindowOpened(event);
1274         }
1275     }
1276 
1277     private void fireWindowClosed(final WebWindowEvent event) {
1278         if (currentWindowTracker_ != null) {
1279             currentWindowTracker_.webWindowClosed(event);
1280         }
1281 
1282         for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1283             listener.webWindowClosed(event);
1284         }
1285 
1286         blobUrlStore_.removeForPage(event.getOldPage());
1287 
1288         // to open a new top level window if all others are gone
1289         if (currentWindowTracker_ != null) {
1290             currentWindowTracker_.afterWebWindowClosedListenersProcessed(event);
1291         }
1292     }
1293 
1294     /**
1295      * Open a new window with the specified name. If the URL is non-null then attempt to load
1296      * a page from that location and put it in the new window.
1297      *
1298      * @param url the URL to load content from or null if no content is to be loaded
1299      * @param windowName the name of the new window
1300      * @return the new window
1301      */
1302     public WebWindow openWindow(final URL url, final String windowName) {
1303         WebAssert.notNull("windowName", windowName);
1304         return openWindow(url, windowName, getCurrentWindow());
1305     }
1306 
1307     /**
1308      * Open a new window with the specified name. If the URL is non-null then attempt to load
1309      * a page from that location and put it in the new window.
1310      *
1311      * @param url the URL to load content from or null if no content is to be loaded
1312      * @param windowName the name of the new window
1313      * @param opener the web window that is calling openWindow
1314      * @return the new window
1315      */
1316     public WebWindow openWindow(final URL url, final String windowName, final WebWindow opener) {
1317         final WebWindow window = openTargetWindow(opener, windowName, TARGET_BLANK);
1318         // a new auxiliary browsing context gets a copy of the opener's session storage
1319         getStorageHolder().copySessionStorage(opener, window);
1320         if (url == null) {
1321             initializeEmptyWindow(window, window.getEnclosedPage());
1322         }
1323         else {
1324             try {
1325                 final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
1326                                                                 getBrowserVersion().getAcceptEncodingHeader());
1327                 request.setCharset(UTF_8);
1328 
1329                 final Page openerPage = opener.getEnclosedPage();
1330                 if (openerPage != null && openerPage.getUrl() != null) {
1331                     request.setRefererHeader(openerPage.getUrl());
1332                     if (openerPage instanceof HtmlPage openerHtmlPage) {
1333                         request.setReferrerPolicy(openerHtmlPage.getReferrerPolicy());
1334                     }
1335                 }
1336                 getPage(window, request);
1337             }
1338             catch (final IOException e) {
1339                 LOG.error("Error loading content into window", e);
1340             }
1341         }
1342         return window;
1343     }
1344 
1345     /**
1346      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1347      *
1348      * Open the window with the specified name. The name may be a special
1349      * target name of _self, _parent, _top, or _blank. An empty or null
1350      * name is set to the default. The special target names are relative to
1351      * the opener window.
1352      *
1353      * @param opener the web window that is calling openWindow
1354      * @param windowName the name of the new window
1355      * @param defaultName the default target if no name is given
1356      * @return the new window
1357      */
1358     public WebWindow openTargetWindow(
1359             final WebWindow opener, final String windowName, final String defaultName) {
1360 
1361         WebAssert.notNull("opener", opener);
1362         WebAssert.notNull("defaultName", defaultName);
1363 
1364         String windowToOpen = windowName;
1365         if (windowToOpen == null || windowToOpen.isEmpty()) {
1366             windowToOpen = defaultName;
1367         }
1368 
1369         WebWindow webWindow = resolveWindow(opener, windowToOpen, true);
1370 
1371         if (webWindow == null) {
1372             if (TARGET_BLANK.equals(windowToOpen)) {
1373                 windowToOpen = "";
1374             }
1375             webWindow = new TopLevelWindow(windowToOpen, this);
1376         }
1377 
1378         if (webWindow instanceof TopLevelWindow window && webWindow != opener.getTopWindow()) {
1379             window.setOpener(opener);
1380         }
1381 
1382         return webWindow;
1383     }
1384 
1385     /**
1386      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1387      *
1388      * Returns the existing window for the given target name (e.g. a frame or a window opened before);
1389      * the name may be a special target name of _self, _parent or _top (relative to the opener window).
1390      * Unlike {@link #openTargetWindow(WebWindow, String, String)} no new window is created.
1391      *
1392      * @param opener the web window that is looking for the target
1393      * @param name the target name
1394      * @return the window or {@code null} if there is no window with this name
1395      */
1396     public WebWindow findTargetWindow(final WebWindow opener, final String name) {
1397         return resolveWindow(opener, name, false);
1398     }
1399 
1400     private WebWindow resolveWindow(final WebWindow opener, final String name, final boolean loadsContent) {
1401         if (name == null || name.isEmpty() || TARGET_SELF.equals(name)) {
1402             return opener;
1403         }
1404 
1405         if (TARGET_PARENT.equals(name)) {
1406             return opener.getParentWindow();
1407         }
1408 
1409         if (TARGET_TOP.equals(name)) {
1410             return opener.getTopWindow();
1411         }
1412 
1413         if (TARGET_BLANK.equals(name)) {
1414             return null;
1415         }
1416 
1417         // first search for frame windows inside our window hierarchy
1418         WebWindow window = opener;
1419         while (true) {
1420             final Page page = window.getEnclosedPage();
1421             if (page != null && page.isHtmlPage()) {
1422                 try {
1423                     final FrameWindow frame = ((HtmlPage) page).getFrameByName(name);
1424                     final HtmlUnitScriptable scriptable = frame.getFrameElement().getScriptableObject();
1425                     if (loadsContent && scriptable instanceof HTMLIFrameElement element) {
1426                         element.onRefresh();
1427                     }
1428                     return frame;
1429                 }
1430                 catch (final ElementNotFoundException expected) {
1431                     // Fall through
1432                 }
1433             }
1434 
1435             if (window == window.getParentWindow()) {
1436                 // TODO: should getParentWindow() return null on top windows?
1437                 break;
1438             }
1439             window = window.getParentWindow();
1440         }
1441 
1442         try {
1443             return getWebWindowByName(name);
1444         }
1445         catch (final WebWindowNotFoundException expected) {
1446             // Fall through - a new window will be created below
1447         }
1448         return null;
1449     }
1450 
1451     /**
1452      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
1453      *
1454      * Opens a new dialog window.
1455      * @param url the URL of the document to load and display
1456      * @param opener the web window that is opening the dialog
1457      * @param dialogArguments the object to make available inside the dialog via <code>window.dialogArguments</code>
1458      * @return the new dialog window
1459      * @throws IOException if there is an IO error
1460      */
1461     public DialogWindow openDialogWindow(final URL url, final WebWindow opener, final Object dialogArguments)
1462         throws IOException {
1463 
1464         WebAssert.notNull("url", url);
1465         WebAssert.notNull("opener", opener);
1466 
1467         final DialogWindow window = new DialogWindow(this, dialogArguments);
1468 
1469         final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
1470         final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
1471                                                         getBrowserVersion().getAcceptEncodingHeader());
1472         request.setCharset(UTF_8);
1473 
1474         if (openerPage != null) {
1475             request.setRefererHeader(openerPage.getUrl());
1476             request.setReferrerPolicy(openerPage.getReferrerPolicy());
1477         }
1478 
1479         getPage(window, request);
1480 
1481         return window;
1482     }
1483 
1484     /**
1485      * Sets the object that will be used to create pages. Set this if you want
1486      * to customize the type of page that is returned for a given content type.
1487      *
1488      * @param pageCreator the new page creator
1489      */
1490     public void setPageCreator(final PageCreator pageCreator) {
1491         WebAssert.notNull("pageCreator", pageCreator);
1492         pageCreator_ = pageCreator;
1493     }
1494 
1495     /**
1496      * Returns the current page creator.
1497      *
1498      * @return the page creator
1499      */
1500     public PageCreator getPageCreator() {
1501         return pageCreator_;
1502     }
1503 
1504     /**
1505      * Returns the first {@link WebWindow} that matches the specified name.
1506      *
1507      * @param name the name to search for
1508      * @return the {@link WebWindow} with the specified name
1509      * @throws WebWindowNotFoundException if the {@link WebWindow} can't be found
1510      * @see #getWebWindows()
1511      * @see #getTopLevelWindows()
1512      */
1513     public WebWindow getWebWindowByName(final String name) throws WebWindowNotFoundException {
1514         WebAssert.notNull("name", name);
1515 
1516         for (final WebWindow webWindow : windows_) {
1517             if (name.equals(webWindow.getName())) {
1518                 return webWindow;
1519             }
1520         }
1521 
1522         throw new WebWindowNotFoundException(name);
1523     }
1524 
1525     /**
1526      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1527      *
1528      * Initializes a new web window for JavaScript.
1529      * @param webWindow the new WebWindow
1530      * @param page the page that will become the enclosing page
1531      */
1532     public void initialize(final WebWindow webWindow, final Page page) {
1533         WebAssert.notNull("webWindow", webWindow);
1534 
1535         if (isJavaScriptEngineEnabled()) {
1536             scriptEngine_.initialize(webWindow, page);
1537         }
1538     }
1539 
1540     /**
1541      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1542      *
1543      * Initializes a new empty window for JavaScript.
1544      *
1545      * @param webWindow the new WebWindow
1546      * @param page the page that will become the enclosing page
1547      */
1548     public void initializeEmptyWindow(final WebWindow webWindow, final Page page) {
1549         WebAssert.notNull("webWindow", webWindow);
1550 
1551         if (isJavaScriptEngineEnabled()) {
1552             initialize(webWindow, page);
1553             ((Window) webWindow.getScriptableObject()).initialize();
1554         }
1555     }
1556 
1557     /**
1558      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1559      *
1560      * Adds a new window to the list of available windows.
1561      *
1562      * @param webWindow the new WebWindow
1563      */
1564     public void registerWebWindow(final WebWindow webWindow) {
1565         WebAssert.notNull("webWindow", webWindow);
1566         if (windows_.add(webWindow)) {
1567             fireWindowOpened(new WebWindowEvent(webWindow, WebWindowEvent.OPEN, webWindow.getEnclosedPage(), null));
1568         }
1569         // register JobManager here but don't deregister in deregisterWebWindow as it can live longer
1570         jobManagers_.add(new WeakReference<>(webWindow.getJobManager()));
1571     }
1572 
1573     /**
1574      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1575      *
1576      * Removes a window from the list of available windows.
1577      *
1578      * @param webWindow the window to remove
1579      */
1580     public void deregisterWebWindow(final WebWindow webWindow) {
1581         WebAssert.notNull("webWindow", webWindow);
1582         if (windows_.remove(webWindow)) {
1583             fireWindowClosed(new WebWindowEvent(webWindow, WebWindowEvent.CLOSE, webWindow.getEnclosedPage(), null));
1584         }
1585     }
1586 
1587     /**
1588      * Registers an object and a cleaning action to run when the object
1589      * becomes phantom reachable. This forwards the call to our static {@link Cleaner}.
1590      *
1591      * @param obj   the object to monitor
1592      * @param action a {@code Runnable} to invoke when the object becomes phantom reachable
1593      * @return a {@code Cleanable} instance
1594      */
1595     public static Cleanable registerCleanerAction(final Object obj, final Runnable action) {
1596         return CLEANER.register(obj, action);
1597     }
1598 
1599     /**
1600      * Expands a relative URL relative to the specified base. In most situations
1601      * this is the same as <code>new URL(baseUrl, relativeUrl)</code> but
1602      * there are some cases that URL doesn't handle correctly. See
1603      * <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>
1604      * regarding Relative Uniform Resource Locators for more information.
1605      *
1606      * @param baseUrl the base URL
1607      * @param relativeUrl the relative URL
1608      * @return the expansion of the specified base and relative URLs
1609      * @throws MalformedURLException if an error occurred when creating a URL object
1610      */
1611     public static URL expandUrl(final URL baseUrl, final String relativeUrl) throws MalformedURLException {
1612         final String newUrl = UrlUtils.resolveUrl(baseUrl, relativeUrl);
1613         return UrlUtils.toUrlUnsafe(newUrl);
1614     }
1615 
1616     private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException {
1617         final URL url = webRequest.getUrl();
1618 
1619         final DataURLConnection connection = new DataURLConnection(url);
1620 
1621         final List<NameValuePair> responseHeaders = new ArrayList<>();
1622         final boolean standardSerialization =
1623                 getBrowserVersion().hasFeature(DATA_URL_MIME_TYPE_STANDARD_SERIALIZATION);
1624         responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC,
1625                 connection.getContentType(standardSerialization)));
1626 
1627         if (HttpMethod.HEAD.equals(webRequest.getHttpMethod())) {
1628             final WebResponseData data = new WebResponseData(200, "OK", responseHeaders);
1629             return new WebResponse(data, webRequest, 0);
1630         }
1631 
1632         try (InputStream is = connection.getInputStream()) {
1633             final DownloadedContent downloadedContent =
1634                     HttpWebConnection.downloadContent(is,
1635                             getOptions().getMaxInMemory(),
1636                             getOptions().getTempFileDirectory());
1637             final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders);
1638             // the request is used for the default charset (e.g. UTF-8 for XMLHttpRequest)
1639             return new WebResponse(data, webRequest, 0);
1640         }
1641     }
1642 
1643     /**
1644      * Builds the response for the document of an iframe with srcdoc attribute (about:srcdoc);
1645      * the content is the value of the srcdoc attribute.
1646      *
1647      * @param webWindow the window the response is loaded into
1648      * @param webRequest the request
1649      * @return the response or {@code null} if the request is not for the srcdoc of a frame
1650      */
1651     private static WebResponse makeWebResponseForSrcdoc(final WebWindow webWindow, final WebRequest webRequest) {
1652         if (webWindow instanceof FrameWindow frameWindow
1653                 && UrlUtils.ABOUT_SRCDOC.equals(webRequest.getUrl().toExternalForm())) {
1654             final String srcdoc = frameWindow.getFrameElement().getAttributeDirect(BaseFrameElement.SRCDOC_ATTRIBUTE);
1655             if (DomElement.ATTRIBUTE_NOT_DEFINED != srcdoc) {
1656                 return new StringWebResponse(srcdoc, UrlUtils.URL_ABOUT_SRCDOC);
1657             }
1658         }
1659         return null;
1660     }
1661 
1662     private static WebResponse makeWebResponseForAboutUrl(final WebRequest webRequest) throws MalformedURLException {
1663         final URL url = webRequest.getUrl();
1664         if (UrlUtils.ABOUT.equals(url.getProtocol())) {
1665             if ("blank".equalsIgnoreCase(url.getPath())) {
1666                 if (url.getRef() == null && url.getQuery() == null) {
1667                     return new StringWebResponse("", UrlUtils.URL_ABOUT_BLANK);
1668                 }
1669                 return new StringWebResponse("", url);
1670             }
1671         }
1672 
1673         throw new MalformedURLException(url + " is not supported, only about:blank is supported at the moment.");
1674     }
1675 
1676     /**
1677      * Builds a WebResponse for a file URL.
1678      * This first implementation is basic.
1679      * It assumes that the file contains an HTML page encoded with the specified encoding.
1680      * @param webRequest the request
1681      * @return the web response
1682      * @throws IOException if an IO problem occurs
1683      */
1684     private WebResponse makeWebResponseForFileUrl(final WebRequest webRequest) throws IOException {
1685         URL cleanUrl = webRequest.getUrl();
1686         if (cleanUrl.getQuery() != null) {
1687             // Get rid of the query portion before trying to load the file.
1688             cleanUrl = UrlUtils.getUrlWithNewQuery(cleanUrl, null);
1689         }
1690         if (cleanUrl.getRef() != null) {
1691             // Get rid of the ref portion before trying to load the file.
1692             cleanUrl = UrlUtils.getUrlWithNewRef(cleanUrl, null);
1693         }
1694 
1695         final WebResponse fromCache = getCache().getCachedResponse(webRequest);
1696         if (fromCache != null) {
1697             return new WebResponseFromCache(fromCache, webRequest);
1698         }
1699 
1700         String fileUrl = cleanUrl.toExternalForm();
1701         fileUrl = URLDecoder.decode(fileUrl, UTF_8);
1702         final File file = new File(fileUrl.substring(5));
1703         if (!file.exists()) {
1704             // construct 404
1705             final List<NameValuePair> compiledHeaders = new ArrayList<>();
1706             compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, MimeType.TEXT_HTML));
1707             final WebResponseData responseData =
1708                 new WebResponseData(
1709                         StringUtils
1710                             .toByteArray("File: " + file.getAbsolutePath(), UTF_8),
1711                     404, "Not Found", compiledHeaders);
1712             return new WebResponse(responseData, webRequest, 0);
1713         }
1714 
1715         final String contentType = guessContentType(file);
1716 
1717         final DownloadedContent content = new DownloadedContent.OnFile(file, false);
1718         final List<NameValuePair> compiledHeaders = new ArrayList<>();
1719         compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, contentType));
1720         compiledHeaders.add(new NameValuePair(HttpHeader.LAST_MODIFIED,
1721                 HttpUtils.formatDate(new Date(file.lastModified()))));
1722         final WebResponseData responseData = new WebResponseData(content, 200, "OK", compiledHeaders);
1723         final WebResponse webResponse = new WebResponse(responseData, webRequest, 0);
1724         getCache().cacheIfPossible(webRequest, webResponse, null);
1725         return webResponse;
1726     }
1727 
1728     private WebResponse makeWebResponseForBlobUrl(final WebRequest webRequest) throws IOException {
1729         final Blob fileOrBlob = blobUrlStore_.resolve(webRequest.getUrl().toString());
1730         if (fileOrBlob == null) {
1731             throw new FileNotFoundException("No entry for '" + webRequest.getUrl() + "' in the BlobUrlStore.");
1732         }
1733 
1734         final List<NameValuePair> headers = new ArrayList<>();
1735         final String type = fileOrBlob.getType();
1736         if (!StringUtils.isEmptyOrNull(type)) {
1737             headers.add(new NameValuePair(HttpHeader.CONTENT_TYPE, fileOrBlob.getType()));
1738         }
1739         if (fileOrBlob instanceof org.htmlunit.javascript.host.file.File file) {
1740             final String fileName = file.getName();
1741             if (!StringUtils.isEmptyOrNull(fileName)) {
1742                 // https://datatracker.ietf.org/doc/html/rfc6266#autoid-10
1743                 headers.add(new NameValuePair(HttpHeader.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\""));
1744             }
1745         }
1746 
1747         final DownloadedContent content = new DownloadedContent.InMemory(fileOrBlob.getBytes());
1748         final WebResponseData responseData = new WebResponseData(content, 200, "OK", headers);
1749         return new WebResponse(responseData, webRequest, 0);
1750     }
1751 
1752     /**
1753      * Tries to guess the content type of the file.<br>
1754      * This utility could be located in a helper class but we can compare this functionality
1755      * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a
1756      * property of the "browser".
1757      * @param file the file
1758      * @return "application/octet-stream" if nothing could be guessed
1759      */
1760     public String guessContentType(final File file) {
1761         final String fileName = file.getName();
1762         final String fileNameLC = fileName.toLowerCase(Locale.ROOT);
1763         if (fileNameLC.endsWith(".xhtml")) {
1764             // Java's mime type map returns application/xml in JDK8.
1765             return MimeType.APPLICATION_XHTML;
1766         }
1767 
1768         // Java's mime type map does not know these in JDK8.
1769         if (fileNameLC.endsWith(".js")) {
1770             return MimeType.TEXT_JAVASCRIPT;
1771         }
1772 
1773         if (fileNameLC.endsWith(".css")) {
1774             return MimeType.TEXT_CSS;
1775         }
1776 
1777         String contentType = null;
1778         if (!fileNameLC.endsWith(".php")) {
1779             contentType = URLConnection.guessContentTypeFromName(fileName);
1780         }
1781         if (contentType == null) {
1782             try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
1783                 contentType = URLConnection.guessContentTypeFromStream(inputStream);
1784             }
1785             catch (final IOException ignored) {
1786                 // Ignore silently.
1787             }
1788         }
1789         if (contentType == null) {
1790             contentType = MimeType.APPLICATION_OCTET_STREAM;
1791         }
1792         return contentType;
1793     }
1794 
1795     private WebResponse makeWebResponseForJavaScriptUrl(final WebWindow webWindow, final URL url,
1796         final Charset charset) throws FailingHttpStatusCodeException, IOException {
1797 
1798         HtmlPage page = null;
1799         if (webWindow instanceof FrameWindow frameWindow) {
1800             page = (HtmlPage) frameWindow.getEnclosedPage();
1801         }
1802         else {
1803             final Page currentPage = webWindow.getEnclosedPage();
1804             if (currentPage instanceof HtmlPage htmlPage) {
1805                 page = htmlPage;
1806             }
1807         }
1808 
1809         if (page == null) {
1810             page = getPage(webWindow, WebRequest.newAboutBlankRequest());
1811         }
1812         final ScriptResult r = page.executeJavaScript(url.toExternalForm(), "JavaScript URL", 1);
1813         if (r.getJavaScriptResult() == null || ScriptResult.isUndefined(r)) {
1814             // No new WebResponse to produce.
1815             return webWindow.getEnclosedPage().getWebResponse();
1816         }
1817 
1818         final String contentString = r.getJavaScriptResult().toString();
1819         final StringWebResponse response = new StringWebResponse(contentString, charset, url);
1820         response.setFromJavascript(true);
1821         return response;
1822     }
1823 
1824     /**
1825      * Loads a {@link WebResponse} from the server.
1826      * @param webRequest the request
1827      * @throws IOException if an IO problem occurs
1828      * @return the WebResponse
1829      */
1830     public WebResponse loadWebResponse(final WebRequest webRequest) throws IOException {
1831         final String protocol = webRequest.getUrl().getProtocol();
1832         return switch (protocol) {
1833             case UrlUtils.ABOUT -> makeWebResponseForAboutUrl(webRequest);
1834             case "file" -> makeWebResponseForFileUrl(webRequest);
1835             case "data" -> makeWebResponseForDataUrl(webRequest);
1836             case "blob" -> makeWebResponseForBlobUrl(webRequest);
1837             case "http", "https" -> loadWebResponseFromWebConnection(webRequest, ALLOWED_REDIRECTIONS_SAME_URL);
1838             default -> throw new IOException("Unsupported protocol '" + protocol + "'");
1839         };
1840     }
1841 
1842     /**
1843      * Sets the {@code Referer} header of the request according to its referrer policy
1844      * (if the request has a referrer and a policy).
1845      *
1846      * @param webRequest the request
1847      */
1848     private void applyReferrerPolicy(final WebRequest webRequest) {
1849         final URL referrer = webRequest.getReferrer();
1850         final ReferrerPolicy policy = webRequest.getReferrerPolicy();
1851         if (referrer == null || policy == null) {
1852             return;
1853         }
1854 
1855         final String value = policy.getReferrer(referrer, webRequest.getUrl(), getBrowserVersion());
1856         if (value == null) {
1857             webRequest.removeAdditionalHeader(HttpHeader.REFERER);
1858         }
1859         else {
1860             webRequest.setAdditionalHeader(HttpHeader.REFERER, value);
1861         }
1862     }
1863 
1864     /**
1865      * Loads a {@link WebResponse} from the server through the WebConnection.
1866      * @param webRequest the request
1867      * @param allowedRedirects the number of allowed redirects remaining
1868      * @throws IOException if an IO problem occurs
1869      * @return the resultant {@link WebResponse}
1870      */
1871     private WebResponse loadWebResponseFromWebConnection(final WebRequest webRequest,
1872         final int allowedRedirects) throws IOException {
1873 
1874         URL url = webRequest.getUrl();
1875         final HttpMethod method = webRequest.getHttpMethod();
1876         final List<NameValuePair> parameters = webRequest.getRequestParameters();
1877 
1878         WebAssert.notNull("url", url);
1879         WebAssert.notNull("method", method);
1880         WebAssert.notNull("parameters", parameters);
1881 
1882         url = UrlUtils.encodeUrl(url, webRequest.getCharset());
1883         webRequest.setUrl(url);
1884         applyReferrerPolicy(webRequest);
1885 
1886         if (LOG.isDebugEnabled()) {
1887             LOG.debug("Load response for " + method + " " + url.toExternalForm());
1888         }
1889 
1890         // If the request settings don't specify a custom proxy, use the default client proxy...
1891         if (webRequest.getProxyHost() == null) {
1892             final ProxyConfig proxyConfig = getOptions().getProxyConfig();
1893             if (proxyConfig.getProxyAutoConfigUrl() != null) {
1894                 if (!UrlUtils.sameFile(new URL(proxyConfig.getProxyAutoConfigUrl()), url)) {
1895                     String content = proxyConfig.getProxyAutoConfigContent();
1896                     if (content == null) {
1897                         content = getPage(proxyConfig.getProxyAutoConfigUrl())
1898                             .getWebResponse().getContentAsString();
1899                         proxyConfig.setProxyAutoConfigContent(content);
1900                     }
1901                     final String allValue = JavaScriptEngine.evaluateProxyAutoConfig(getBrowserVersion(), content, url);
1902                     if (LOG.isDebugEnabled()) {
1903                         LOG.debug("Proxy Auto-Config: value '" + allValue + "' for URL " + url);
1904                     }
1905                     String value = allValue.split(";")[0].trim();
1906                     if (value.startsWith("PROXY")) {
1907                         value = value.substring(6);
1908                         final int colonIndex = value.indexOf(':');
1909                         webRequest.setSocksProxy(false);
1910                         webRequest.setProxyHost(value.substring(0, colonIndex));
1911                         webRequest.setProxyPort(Integer.parseInt(value.substring(colonIndex + 1)));
1912                     }
1913                     else if (value.startsWith("SOCKS")) {
1914                         value = value.substring(6);
1915                         final int colonIndex = value.indexOf(':');
1916                         webRequest.setSocksProxy(true);
1917                         webRequest.setProxyHost(value.substring(0, colonIndex));
1918                         webRequest.setProxyPort(Integer.parseInt(value.substring(colonIndex + 1)));
1919                     }
1920                 }
1921             }
1922             // ...unless the host needs to bypass the configured client proxy!
1923             else if (!proxyConfig.shouldBypassProxy(webRequest.getUrl().getHost())) {
1924                 webRequest.setProxyHost(proxyConfig.getProxyHost());
1925                 webRequest.setProxyPort(proxyConfig.getProxyPort());
1926                 webRequest.setProxyScheme(proxyConfig.getProxyScheme());
1927                 webRequest.setSocksProxy(proxyConfig.isSocksProxy());
1928             }
1929         }
1930 
1931         // Add the headers that are sent with every request.
1932         addDefaultHeaders(webRequest);
1933 
1934         // Retrieve the response, either from the cache or from the server.
1935         final WebRequest.CacheMode cacheMode = webRequest.getCacheMode();
1936         addCacheModeHeaders(webRequest, cacheMode);
1937         final WebResponse fromCache = cacheMode == WebRequest.CacheMode.NO_STORE
1938                                         || cacheMode == WebRequest.CacheMode.RELOAD
1939                                     ? null
1940                                     : getCache().getCachedResponse(webRequest);
1941         if (fromCache == null && cacheMode == WebRequest.CacheMode.ONLY_IF_CACHED) {
1942             throw new IOException("No cached response for '" + webRequest.getUrl()
1943                     + "' (cache mode 'only-if-cached').");
1944         }
1945         final WebResponse webResponse = getWebResponseOrUseCached(webRequest, fromCache);
1946 
1947         // Continue according to the HTTP status code.
1948         final int status = webResponse.getStatusCode();
1949         if (status == HttpStatus.USE_PROXY_305) {
1950             getIncorrectnessListener().notify("Ignoring HTTP status code [305] 'Use Proxy'", this);
1951         }
1952         else if (status >= HttpStatus.MOVED_PERMANENTLY_301
1953             && status <= HttpStatus.PERMANENT_REDIRECT_308
1954             && status != HttpStatus.NOT_MODIFIED_304
1955             && getOptions().isRedirectEnabled()
1956             && !webRequest.hasHint(WebRequest.HttpHint.DoNotFollowRedirects)) {
1957 
1958             URL newUrl;
1959             String locationString = null;
1960             try {
1961                 locationString = webResponse.getResponseHeaderValue("Location");
1962                 if (locationString == null) {
1963                     return webResponse;
1964                 }
1965                 locationString = new String(locationString.getBytes(ISO_8859_1), UTF_8);
1966                 newUrl = expandUrl(url, locationString);
1967             }
1968             catch (final MalformedURLException e) {
1969                 getIncorrectnessListener().notify("Got a redirect status code [" + status + " "
1970                     + webResponse.getStatusMessage()
1971                     + "] but the location is not a valid URL [" + locationString
1972                     + "]. Skipping redirection processing.", this);
1973                 return webResponse;
1974             }
1975 
1976             if (LOG.isDebugEnabled()) {
1977                 LOG.debug("Got a redirect status code [" + status + "] new location = [" + locationString + "]");
1978             }
1979 
1980             if (allowedRedirects == 0) {
1981                 throw new FailingHttpStatusCodeException("Too many redirects for "
1982                     + webResponse.getWebRequest().getUrl(), webResponse);
1983             }
1984 
1985             final UnaryOperator<URL> redirectUrlMapper = webRequest.getRedirectUrlMapper();
1986             if (redirectUrlMapper != null) {
1987                 newUrl = redirectUrlMapper.apply(newUrl);
1988             }
1989 
1990             // Fetch standard: a redirect to an url that is not http(s) (e.g. a local file) is a network error
1991             final String newProtocol = newUrl.getProtocol();
1992             if (!"http".equals(newProtocol) && !"https".equals(newProtocol)) {
1993                 throw new IOException("Redirect to the non HTTP(S) url '" + newUrl + "' is not allowed ("
1994                         + webResponse.getWebRequest().getUrl() + ")");
1995             }
1996 
1997             final Predicate<URL> redirectFilter = webRequest.getRedirectFilter();
1998             if (redirectFilter != null && !redirectFilter.test(newUrl)) {
1999                 if (LOG.isDebugEnabled()) {
2000                     LOG.debug("Redirect to [" + newUrl + "] blocked by the redirect filter");
2001                 }
2002                 return null;
2003             }
2004 
2005             final boolean crossOriginRedirect = !UrlUtils.isSameOrigin(url, newUrl);
2006 
2007             if (status == HttpStatus.MOVED_PERMANENTLY_301
2008                     || status == HttpStatus.FOUND_302
2009                     || status == HttpStatus.SEE_OTHER_303) {
2010                 final WebRequest wrs = new WebRequest(newUrl, HttpMethod.GET);
2011                 wrs.setCharset(webRequest.getCharset());
2012 
2013                 if (HttpMethod.HEAD == webRequest.getHttpMethod()) {
2014                     wrs.setHttpMethod(HttpMethod.HEAD);
2015                 }
2016                 for (final Map.Entry<String, String> entry : webRequest.getAdditionalHeaders().entrySet()) {
2017                     wrs.setAdditionalHeader(entry.getKey(), entry.getValue());
2018                 }
2019                 if (crossOriginRedirect) {
2020                     // credentials are not forwarded to another origin
2021                     wrs.removeAdditionalHeader("Authorization");
2022                 }
2023                 // the Referer header is determined again for the new url
2024                 wrs.setRefererHeader(webRequest.getReferrer());
2025                 wrs.setReferrerPolicy(webRequest.getReferrerPolicy());
2026                 wrs.setFetchDestination(webRequest.getFetchDestination());
2027                 wrs.setFetchModeOverride(webRequest.getFetchModeOverride());
2028                 wrs.setRequestingUrl(webRequest.getRequestingUrl());
2029                 wrs.setSiteForCookies(webRequest.getSiteForCookies());
2030                 wrs.setRedirectFilter(redirectFilter);
2031                 wrs.setRedirectUrlMapper(redirectUrlMapper);
2032 
2033                 return loadWebResponseFromWebConnection(wrs, allowedRedirects - 1);
2034             }
2035             else if (status == HttpStatus.TEMPORARY_REDIRECT_307
2036                         || status == HttpStatus.PERMANENT_REDIRECT_308) {
2037                 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307
2038                 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
2039                 // reuse method and body
2040                 final WebRequest wrs = new WebRequest(newUrl, webRequest.getHttpMethod());
2041                 wrs.setCharset(webRequest.getCharset());
2042                 if (webRequest.getRequestBody() != null) {
2043                     if (HttpMethod.POST == webRequest.getHttpMethod()
2044                             || HttpMethod.PUT == webRequest.getHttpMethod()
2045                             || HttpMethod.PATCH == webRequest.getHttpMethod()) {
2046                         wrs.setRequestBody(webRequest.getRequestBody());
2047                         wrs.setEncodingType(webRequest.getEncodingType());
2048                     }
2049                 }
2050                 else {
2051                     wrs.setRequestParameters(parameters);
2052                 }
2053 
2054                 for (final Map.Entry<String, String> entry : webRequest.getAdditionalHeaders().entrySet()) {
2055                     wrs.setAdditionalHeader(entry.getKey(), entry.getValue());
2056                 }
2057                 if (crossOriginRedirect) {
2058                     // credentials are not forwarded to another origin
2059                     wrs.removeAdditionalHeader("Authorization");
2060                 }
2061                 // the Referer header is determined again for the new url
2062                 wrs.setRefererHeader(webRequest.getReferrer());
2063                 wrs.setReferrerPolicy(webRequest.getReferrerPolicy());
2064                 wrs.setRedirectFilter(redirectFilter);
2065                 wrs.setRedirectUrlMapper(redirectUrlMapper);
2066 
2067                 return loadWebResponseFromWebConnection(wrs, allowedRedirects - 1);
2068             }
2069         }
2070 
2071         if (fromCache == null && cacheMode != WebRequest.CacheMode.NO_STORE) {
2072             getCache().cacheIfPossible(webRequest, webResponse, null);
2073         }
2074         return webResponse;
2075     }
2076 
2077     /**
2078      * Adds the headers the fetch standard requires for the cache mode
2079      * (only if the request does not already have them).
2080      *
2081      * @param webRequest the request
2082      * @param cacheMode the cache mode
2083      * @see <a href="https://fetch.spec.whatwg.org/#http-network-or-cache-fetch">Fetch Standard
2084      *      - HTTP-network-or-cache fetch</a>
2085      */
2086     private static void addCacheModeHeaders(final WebRequest webRequest, final WebRequest.CacheMode cacheMode) {
2087         if (cacheMode == WebRequest.CacheMode.NO_STORE || cacheMode == WebRequest.CacheMode.RELOAD) {
2088             if (webRequest.getAdditionalHeader("Pragma") == null) {
2089                 webRequest.setAdditionalHeader("Pragma", "no-cache");
2090             }
2091             if (webRequest.getAdditionalHeader(HttpHeader.CACHE_CONTROL) == null) {
2092                 webRequest.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "no-cache");
2093             }
2094         }
2095         else if (cacheMode == WebRequest.CacheMode.NO_CACHE
2096                 && webRequest.getAdditionalHeader(HttpHeader.CACHE_CONTROL) == null) {
2097             webRequest.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "max-age=0");
2098         }
2099     }
2100 
2101     /**
2102      * Returns the cached response provided for the request if usable otherwise makes the
2103      * request and returns the response.
2104      * @param webRequest the request
2105      * @param cached a previous cached response for the request, or {@code null}
2106      */
2107     private WebResponse getWebResponseOrUseCached(
2108             final WebRequest webRequest, final WebResponse cached) throws IOException {
2109         if (cached == null) {
2110             return getWebConnection().getResponse(webRequest);
2111         }
2112 
2113         final WebRequest.CacheMode cacheMode = webRequest.getCacheMode();
2114         if (cacheMode == WebRequest.CacheMode.FORCE_CACHE || cacheMode == WebRequest.CacheMode.ONLY_IF_CACHED
2115                 || cacheMode != WebRequest.CacheMode.NO_CACHE && !HeaderUtils.containsNoCache(cached)) {
2116             return new WebResponseFromCache(cached, webRequest);
2117         }
2118 
2119         // implementation based on rfc9111 https://www.rfc-editor.org/rfc/rfc9111#name-validation
2120         if (HeaderUtils.containsETag(cached)) {
2121             webRequest.setAdditionalHeader(HttpHeader.IF_NONE_MATCH, cached.getResponseHeaderValue(HttpHeader.ETAG));
2122         }
2123         if (HeaderUtils.containsLastModified(cached)) {
2124             webRequest.setAdditionalHeader(HttpHeader.IF_MODIFIED_SINCE,
2125                     cached.getResponseHeaderValue(HttpHeader.LAST_MODIFIED));
2126         }
2127 
2128         final WebResponse webResponse = getWebConnection().getResponse(webRequest);
2129 
2130         if (webResponse.getStatusCode() >= HttpStatus.INTERNAL_SERVER_ERROR_500) {
2131             return new WebResponseFromCache(cached, webRequest);
2132         }
2133 
2134         if (webResponse.getStatusCode() == HttpStatus.NOT_MODIFIED_304) {
2135             final Map<String, NameValuePair> header2NameValuePair = new LinkedHashMap<>();
2136             for (final NameValuePair pair : cached.getResponseHeaders()) {
2137                 header2NameValuePair.put(pair.getName(), pair);
2138             }
2139             for (final NameValuePair pair : webResponse.getResponseHeaders()) {
2140                 if (preferHeaderFrom304Response(pair.getName())) {
2141                     header2NameValuePair.put(pair.getName(), pair);
2142                 }
2143             }
2144             // WebResponse headers is unmodifiableList so we cannot update it directly
2145             // instead, create a new WebResponseFromCache with updated headers
2146             // then use it to replace the old cached value
2147             final WebResponse updatedCached =
2148                     new WebResponseFromCache(cached, new ArrayList<>(header2NameValuePair.values()), webRequest);
2149             getCache().cacheIfPossible(webRequest, updatedCached, null);
2150             return updatedCached;
2151         }
2152 
2153         getCache().cacheIfPossible(webRequest, webResponse, null);
2154         return webResponse;
2155     }
2156 
2157     /**
2158      * Returns true if the value of the specified header in a 304 Not Modified response should be
2159      * adopted over any previously cached value.
2160      */
2161     private static boolean preferHeaderFrom304Response(final String name) {
2162         final String lcName = name.toLowerCase(Locale.ROOT);
2163         for (final String header : DISCARDING_304_RESPONSE_HEADER_NAMES) {
2164             if (lcName.equals(header)) {
2165                 return false;
2166             }
2167         }
2168         for (final String prefix : DISCARDING_304_HEADER_PREFIXES) {
2169             if (lcName.startsWith(prefix)) {
2170                 return false;
2171             }
2172         }
2173         return true;
2174     }
2175 
2176     /**
2177      * Adds the headers that are sent with every request to the specified {@link WebRequest} instance.
2178      * @param wrs the <code>WebRequestSettings</code> instance to modify
2179      */
2180     private void addDefaultHeaders(final WebRequest wrs) {
2181         // Add user-specified headers to the web request if not present there yet.
2182         requestHeaders_.forEach((name, value) -> {
2183             if (!wrs.isAdditionalHeader(name)) {
2184                 wrs.setAdditionalHeader(name, value);
2185             }
2186         });
2187 
2188         // Add standard HtmlUnit headers to the web request if still not present there yet.
2189         if (!wrs.isAdditionalHeader(HttpHeader.ACCEPT_LANGUAGE)) {
2190             wrs.setAdditionalHeader(HttpHeader.ACCEPT_LANGUAGE, getBrowserVersion().getAcceptLanguageHeader());
2191         }
2192 
2193         // the sec- stuff is done later in the HttpWebConnection
2194         // this implies that stuff is not visible in the MockWebConnection
2195     }
2196 
2197     /**
2198      * Returns an immutable list of open web windows (whether they are top level windows or not).
2199      * This is a snapshot; future changes are not reflected by this list.
2200      * <p>
2201      * The list is ordered by age, the oldest one first.
2202      * </p>
2203      *
2204      * @return an immutable list of open web windows (whether they are top level windows or not)
2205      * @see #getWebWindowByName(String)
2206      * @see #getTopLevelWindows()
2207      */
2208     public List<WebWindow> getWebWindows() {
2209         return List.copyOf(windows_);
2210     }
2211 
2212     /**
2213      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2214      *
2215      * Returns true if the list of WebWindows contains the provided one.
2216      * This method is there to improve the performance of some internal checks because
2217      * calling getWebWindows().contains(.) creates some objects without any need.
2218      *
2219      * @param webWindow the window to check
2220      * @return true or false
2221      */
2222     public boolean containsWebWindow(final WebWindow webWindow) {
2223         return windows_.contains(webWindow);
2224     }
2225 
2226     /**
2227      * Returns an immutable list of open top level windows.
2228      * This is a snapshot; future changes are not reflected by this list.
2229      * <p>
2230      * The list is ordered by age, the oldest one first.
2231      * </p>
2232      *
2233      * @return an immutable list of open top level windows
2234      * @see #getWebWindowByName(String)
2235      * @see #getWebWindows()
2236      */
2237     public List<TopLevelWindow> getTopLevelWindows() {
2238         return List.copyOf(topLevelWindows_);
2239     }
2240 
2241     /**
2242      * Sets the handler to be used whenever a refresh is triggered. Refer
2243      * to the documentation for {@link RefreshHandler} for more details.
2244      * @param handler the new handler
2245      */
2246     public void setRefreshHandler(final RefreshHandler handler) {
2247         if (handler == null) {
2248             refreshHandler_ = new NiceRefreshHandler(2);
2249         }
2250         else {
2251             refreshHandler_ = handler;
2252         }
2253     }
2254 
2255     /**
2256      * Returns the current refresh handler.
2257      * The default refresh handler is a {@link NiceRefreshHandler NiceRefreshHandler(2)}.
2258      * @return the current RefreshHandler
2259      */
2260     public RefreshHandler getRefreshHandler() {
2261         return refreshHandler_;
2262     }
2263 
2264     /**
2265      * Sets the script pre processor for this {@link WebClient}.
2266      * @param scriptPreProcessor the new preprocessor or null if none is specified
2267      */
2268     public void setScriptPreProcessor(final ScriptPreProcessor scriptPreProcessor) {
2269         scriptPreProcessor_ = scriptPreProcessor;
2270     }
2271 
2272     /**
2273      * Returns the script pre processor for this {@link WebClient}.
2274      * @return the pre processor or null of one hasn't been set
2275      */
2276     public ScriptPreProcessor getScriptPreProcessor() {
2277         return scriptPreProcessor_;
2278     }
2279 
2280     /**
2281      * Sets the listener for messages generated by the HTML parser.
2282      * @param listener the new listener, {@code null} if messages should be totally ignored
2283      */
2284     public void setHTMLParserListener(final HTMLParserListener listener) {
2285         htmlParserListener_ = listener;
2286     }
2287 
2288     /**
2289      * Gets the configured listener for messages generated by the HTML parser.
2290      * @return {@code null} if no listener is defined (default value)
2291      */
2292     public HTMLParserListener getHTMLParserListener() {
2293         return htmlParserListener_;
2294     }
2295 
2296     /**
2297      * Returns the CSS error handler used by this web client when CSS problems are encountered.
2298      * @return the CSS error handler used by this web client when CSS problems are encountered
2299      * @see DefaultCssErrorHandler
2300      * @see SilentCssErrorHandler
2301      */
2302     public CSSErrorHandler getCssErrorHandler() {
2303         return cssErrorHandler_;
2304     }
2305 
2306     /**
2307      * Sets the CSS error handler used by this web client when CSS problems are encountered.
2308      * @param cssErrorHandler the CSS error handler used by this web client when CSS problems are encountered
2309      * @see DefaultCssErrorHandler
2310      * @see SilentCssErrorHandler
2311      */
2312     public void setCssErrorHandler(final CSSErrorHandler cssErrorHandler) {
2313         WebAssert.notNull("cssErrorHandler", cssErrorHandler);
2314         cssErrorHandler_ = cssErrorHandler;
2315     }
2316 
2317     /**
2318      * Sets the number of milliseconds that a script is allowed to execute before being terminated.
2319      * A value of 0 or less means no timeout.
2320      *
2321      * @param timeout the timeout value, in milliseconds
2322      */
2323     public void setJavaScriptTimeout(final long timeout) {
2324         scriptEngine_.setJavaScriptTimeout(timeout);
2325     }
2326 
2327     /**
2328      * Returns the number of milliseconds that a script is allowed to execute before being terminated.
2329      * A value of 0 or less means no timeout.
2330      *
2331      * @return the timeout value, in milliseconds
2332      */
2333     public long getJavaScriptTimeout() {
2334         return scriptEngine_.getJavaScriptTimeout();
2335     }
2336 
2337     /**
2338      * Gets the current listener for encountered incorrectness (except HTML parsing messages that
2339      * are handled by the HTML parser listener). Default value is an instance of
2340      * {@link IncorrectnessListenerImpl}.
2341      * @return the current listener (not {@code null})
2342      */
2343     public IncorrectnessListener getIncorrectnessListener() {
2344         return incorrectnessListener_;
2345     }
2346 
2347     /**
2348      * Returns the current HTML incorrectness listener.
2349      * @param listener the new value (not {@code null})
2350      */
2351     public void setIncorrectnessListener(final IncorrectnessListener listener) {
2352         if (listener == null) {
2353             throw new IllegalArgumentException("Null is not a valid IncorrectnessListener");
2354         }
2355         incorrectnessListener_ = listener;
2356     }
2357 
2358     /**
2359      * Returns the WebConsole.
2360      * @return the web console
2361      */
2362     public WebConsole getWebConsole() {
2363         if (webConsole_ == null) {
2364             webConsole_ = new WebConsole();
2365         }
2366         return webConsole_;
2367     }
2368 
2369     /**
2370      * Gets the current AJAX controller.
2371      * @return the controller
2372      */
2373     public AjaxController getAjaxController() {
2374         return ajaxController_;
2375     }
2376 
2377     /**
2378      * Sets the current AJAX controller.
2379      * @param newValue the controller
2380      */
2381     public void setAjaxController(final AjaxController newValue) {
2382         if (newValue == null) {
2383             throw new IllegalArgumentException("Null is not a valid AjaxController");
2384         }
2385         ajaxController_ = newValue;
2386     }
2387 
2388     /**
2389      * Sets the attachment handler.
2390      * @param handler the new attachment handler
2391      */
2392     public void setAttachmentHandler(final AttachmentHandler handler) {
2393         attachmentHandler_ = handler;
2394     }
2395 
2396     /**
2397      * Returns the current attachment handler.
2398      * @return the current attachment handler
2399      */
2400     public AttachmentHandler getAttachmentHandler() {
2401         return attachmentHandler_;
2402     }
2403 
2404     /**
2405      * Sets the WebStart handler.
2406      * @param handler the new WebStart handler
2407      */
2408     public void setWebStartHandler(final WebStartHandler handler) {
2409         webStartHandler_ = handler;
2410     }
2411 
2412     /**
2413      * Returns the current WebStart handler.
2414      * @return the current WebStart handler
2415      */
2416     public WebStartHandler getWebStartHandler() {
2417         return webStartHandler_;
2418     }
2419 
2420     /**
2421      * Returns the current clipboard handler.
2422      * @return the current clipboard handler
2423      */
2424     public ClipboardHandler getClipboardHandler() {
2425         return clipboardHandler_;
2426     }
2427 
2428     /**
2429      * Sets the clipboard handler.
2430      * @param handler the new clipboard handler
2431      */
2432     public void setClipboardHandler(final ClipboardHandler handler) {
2433         clipboardHandler_ = handler;
2434     }
2435 
2436     /**
2437      * Returns the current {@link PrintHandler}.
2438      * @return the current {@link PrintHandler} or null if print
2439      *         requests are ignored
2440      */
2441     public PrintHandler getPrintHandler() {
2442         return printHandler_;
2443     }
2444 
2445     /**
2446      * Sets the {@link PrintHandler} to be used if Windoe.print() is called
2447      * (<a href="https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#printing">Printing Spec</a>).
2448      *
2449      * @param handler the new {@link PrintHandler} or null if you like to
2450      *        ignore print requests (default is null)
2451      */
2452     public void setPrintHandler(final PrintHandler handler) {
2453         printHandler_ = handler;
2454     }
2455 
2456     /**
2457      * Returns the current FrameContent handler.
2458      * @return the current FrameContent handler
2459      */
2460     public FrameContentHandler getFrameContentHandler() {
2461         return frameContentHandler_;
2462     }
2463 
2464     /**
2465      * Sets the FrameContent handler.
2466      * @param handler the new FrameContent handler
2467      */
2468     public void setFrameContentHandler(final FrameContentHandler handler) {
2469         frameContentHandler_ = handler;
2470     }
2471 
2472     /**
2473      * Sets the onbeforeunload handler for this {@link WebClient}.
2474      * @param onbeforeunloadHandler the new onbeforeunloadHandler or null if none is specified
2475      */
2476     public void setOnbeforeunloadHandler(final OnbeforeunloadHandler onbeforeunloadHandler) {
2477         onbeforeunloadHandler_ = onbeforeunloadHandler;
2478     }
2479 
2480     /**
2481      * Returns the onbeforeunload handler for this {@link WebClient}.
2482      * @return the onbeforeunload handler or null if one hasn't been set
2483      */
2484     public OnbeforeunloadHandler getOnbeforeunloadHandler() {
2485         return onbeforeunloadHandler_;
2486     }
2487 
2488     /**
2489      * Gets the cache currently being used.
2490      * @return the cache (may not be null)
2491      */
2492     public Cache getCache() {
2493         return cache_;
2494     }
2495 
2496     /**
2497      * Sets the cache to use.
2498      * @param cache the new cache (must not be {@code null})
2499      */
2500     public void setCache(final Cache cache) {
2501         if (cache == null) {
2502             throw new IllegalArgumentException("cache should not be null!");
2503         }
2504         cache_ = cache;
2505     }
2506 
2507     /**
2508      * Keeps track of the current window. Inspired by WebTest's logic to track the current response.
2509      */
2510     private static final class CurrentWindowTracker implements WebWindowListener, Serializable {
2511         private final WebClient webClient_;
2512         private final boolean ensureOneTopLevelWindow_;
2513 
2514         CurrentWindowTracker(final WebClient webClient, final boolean ensureOneTopLevelWindow) {
2515             webClient_ = webClient;
2516             ensureOneTopLevelWindow_ = ensureOneTopLevelWindow;
2517         }
2518 
2519         /**
2520          * {@inheritDoc}
2521          */
2522         @Override
2523         public void webWindowClosed(final WebWindowEvent event) {
2524             final WebWindow window = event.getWebWindow();
2525             if (window instanceof TopLevelWindow) {
2526                 webClient_.topLevelWindows_.remove(window);
2527                 if (window == webClient_.getCurrentWindow()) {
2528                     if (!webClient_.topLevelWindows_.isEmpty()) {
2529                         // The current window is now the previous top-level window.
2530                         webClient_.setCurrentWindow(
2531                                 webClient_.topLevelWindows_.get(webClient_.topLevelWindows_.size() - 1));
2532                     }
2533                 }
2534             }
2535             else if (window == webClient_.getCurrentWindow()) {
2536                 // The current window is now the last top-level window.
2537                 if (webClient_.topLevelWindows_.isEmpty()) {
2538                     webClient_.setCurrentWindow(null);
2539                 }
2540                 else {
2541                     webClient_.setCurrentWindow(
2542                             webClient_.topLevelWindows_.get(webClient_.topLevelWindows_.size() - 1));
2543                 }
2544             }
2545         }
2546 
2547         /**
2548          * Postprocessing to make sure we have always one top level window open.
2549          */
2550         public void afterWebWindowClosedListenersProcessed(final WebWindowEvent event) {
2551             if (!ensureOneTopLevelWindow_) {
2552                 return;
2553             }
2554 
2555             if (webClient_.topLevelWindows_.isEmpty()) {
2556                 // Must always have at least window, and there are no top-level windows left; must create one.
2557                 final TopLevelWindow newWindow = new TopLevelWindow("", webClient_);
2558                 webClient_.setCurrentWindow(newWindow);
2559             }
2560         }
2561 
2562         /**
2563          * {@inheritDoc}
2564          */
2565         @Override
2566         public void webWindowContentChanged(final WebWindowEvent event) {
2567             final WebWindow window = event.getWebWindow();
2568             boolean use = false;
2569             if (window instanceof DialogWindow) {
2570                 use = true;
2571             }
2572             else if (window instanceof TopLevelWindow) {
2573                 use = event.getOldPage() == null;
2574             }
2575             else if (window instanceof FrameWindow fw) {
2576                 final String enclosingPageState = fw.getEnclosingPage().getDocumentElement().getReadyState();
2577                 final URL frameUrl = fw.getEnclosedPage().getUrl();
2578                 if (!DomNode.READY_STATE_COMPLETE.equals(enclosingPageState) || frameUrl == UrlUtils.URL_ABOUT_BLANK) {
2579                     return;
2580                 }
2581 
2582                 // now looks at the visibility of the frame window
2583                 final BaseFrameElement frameElement = fw.getFrameElement();
2584                 if (webClient_.isJavaScriptEnabled() && frameElement.isDisplayed()) {
2585                     final ComputedCssStyleDeclaration style = fw.getComputedStyle(frameElement, null);
2586                     use = style.getCalculatedWidth(false, false) != 0
2587                             && style.getCalculatedHeight(false, false) != 0;
2588                 }
2589             }
2590             if (use) {
2591                 webClient_.setCurrentWindow(window);
2592             }
2593         }
2594 
2595         /**
2596          * {@inheritDoc}
2597          */
2598         @Override
2599         public void webWindowOpened(final WebWindowEvent event) {
2600             final WebWindow window = event.getWebWindow();
2601             if (window instanceof TopLevelWindow tlw) {
2602                 webClient_.topLevelWindows_.add(tlw);
2603             }
2604             // Page is not loaded yet, don't set it now as current window.
2605         }
2606     }
2607 
2608     /**
2609      * Closes all opened windows, stopping all background JavaScript processing.
2610      * The WebClient is not really usable after this - you have to create a new one or
2611      * use WebClient.reset() instead.
2612      */
2613     @Override
2614     public void close() {
2615         // avoid attaching new windows to the js engine
2616         if (scriptEngine_ != null) {
2617             scriptEngine_.prepareShutdown();
2618         }
2619 
2620         // stop the CurrentWindowTracker from making sure there is still one window available
2621         currentWindowTracker_ = new CurrentWindowTracker(this, false);
2622 
2623         // Hint: a new TopLevelWindow may be opened by some JS script while we are closing the others
2624         // but the prepareShutdown() call will prevent the new window form getting js support
2625         List<WebWindow> windows = new ArrayList<>(windows_);
2626         for (final WebWindow window : windows) {
2627             if (window instanceof TopLevelWindow topLevelWindow) {
2628 
2629                 try {
2630                     topLevelWindow.close(true);
2631                 }
2632                 catch (final Exception e) {
2633                     LOG.error("Exception while closing a TopLevelWindow", e);
2634                 }
2635             }
2636             else if (window instanceof DialogWindow dialogWindow) {
2637 
2638                 try {
2639                     dialogWindow.close();
2640                 }
2641                 catch (final Exception e) {
2642                     LOG.error("Exception while closing a DialogWindow", e);
2643                 }
2644             }
2645         }
2646 
2647         // second round, none of the remaining windows should be registered to
2648         // the js engine because of prepareShutdown()
2649         windows = new ArrayList<>(windows_);
2650         for (final WebWindow window : windows) {
2651             if (window instanceof TopLevelWindow topLevelWindow) {
2652 
2653                 try {
2654                     topLevelWindow.close(true);
2655                 }
2656                 catch (final Exception e) {
2657                     LOG.error("Exception while closing a TopLevelWindow", e);
2658                 }
2659             }
2660             else if (window instanceof DialogWindow dialogWindow) {
2661 
2662                 try {
2663                     dialogWindow.close();
2664                 }
2665                 catch (final Exception e) {
2666                     LOG.error("Exception while closing a DialogWindow", e);
2667                 }
2668             }
2669         }
2670 
2671         // now both lists have to be empty
2672         if (!topLevelWindows_.isEmpty()) {
2673             LOG.error("Sill " + topLevelWindows_.size() + " top level windows are open. Please report this error!");
2674             topLevelWindows_.clear();
2675         }
2676 
2677         if (!windows_.isEmpty()) {
2678             LOG.error("Sill " + windows_.size() + " windows are open. Please report this error!");
2679             windows_.clear();
2680         }
2681         currentWindow_ = null;
2682 
2683         ThreadDeath toThrow = null;
2684         if (scriptEngine_ != null) {
2685             try {
2686                 scriptEngine_.shutdown();
2687             }
2688             catch (final ThreadDeath ex) {
2689                 // make sure the following cleanup is performed to avoid resource leaks
2690                 toThrow = ex;
2691             }
2692             catch (final Exception e) {
2693                 LOG.error("Exception while shutdown the scriptEngine", e);
2694             }
2695         }
2696         scriptEngine_ = null;
2697 
2698         if (webConnection_ != null) {
2699             try {
2700                 webConnection_.close();
2701             }
2702             catch (final Exception e) {
2703                 LOG.error("Exception while closing the connection", e);
2704             }
2705         }
2706         webConnection_ = null;
2707 
2708         synchronized (executorLock_) {
2709             if (executor_ != null) {
2710                 try {
2711                     executor_.shutdownNow();
2712                 }
2713                 catch (final Exception e) {
2714                     LOG.error("Exception while shutdown the executor service", e);
2715                 }
2716             }
2717             executor_ = null;
2718         }
2719 
2720         cache_.clear();
2721         if (toThrow != null) {
2722             throw toThrow;
2723         }
2724     }
2725 
2726     /**
2727      * <p><span style="color:red">Experimental API: May be changed in next release
2728      * and may not yet work perfectly!.</span></p>
2729      *
2730      * <p>This shuts down the whole client and restarts with a new empty window.
2731      * Cookies and other states are preserved.
2732      * </p>
2733      */
2734     public void reset() {
2735         close();
2736 
2737         // this has to be done after the browser version was set
2738         webConnection_ = new HttpWebConnection(this);
2739         if (javaScriptEngineEnabled_) {
2740             scriptEngine_ = new JavaScriptEngine(this);
2741         }
2742 
2743         // The window must be constructed AFTER the script engine.
2744         currentWindowTracker_ = new CurrentWindowTracker(this, true);
2745         currentWindow_ = new TopLevelWindow("", this);
2746     }
2747 
2748     /**
2749      * <p>Blocks until all background JavaScript tasks have finished executing or until the specified
2750      * timeout is reached, whichever occurs first. Background JavaScript tasks include:</p>
2751      * <ul>
2752      *   <li>JavaScript scheduled via <code>window.setTimeout()</code></li>
2753      *   <li>JavaScript scheduled via <code>window.setInterval()</code></li>
2754      *   <li>Asynchronous <code>XMLHttpRequest</code> operations</li>
2755      *   <li>Other asynchronous JavaScript operations across all windows managed by this WebClient</li>
2756      * </ul>
2757      *
2758      * <p><strong>Timeout Behavior:</strong> If background tasks are scheduled to execute after
2759      * <code>(now + timeoutMillis)</code>, this method will wait for the full timeout duration
2760      * and then return the number of remaining jobs. The method guarantees it will never block
2761      * longer than the specified timeout.</p>
2762      *
2763      * <p><strong>Use Case:</strong> Use this method when you don't know the exact timing of when
2764      * background JavaScript will start, but you have a reasonable estimate of how long all
2765      * tasks should take to complete. For scenarios where you know when tasks should start
2766      * executing, consider using {@link #waitForBackgroundJavaScriptStartingBefore(long)} instead.</p>
2767      *
2768      * <p><strong>Thread Safety:</strong> This method is thread-safe and handles concurrent
2769      * modifications to the internal job manager list gracefully.</p>
2770      *
2771      * <p><strong>Example Usage:</strong></p>
2772      * <pre><code>
2773      * // Wait up to 5 seconds for all background JavaScript to complete
2774      * int remainingJobs = webClient.waitForBackgroundJavaScript(5000);
2775      * if (remainingJobs == 0) {
2776      *     log("All background JavaScript completed");
2777      * } else {
2778      *     log("Timeout reached, " + remainingJobs + " jobs still pending");
2779      * }
2780      * </code></pre>
2781      *
2782      * @param timeoutMillis the maximum amount of time to wait in milliseconds; must be positive
2783      * @return the number of background JavaScript jobs still executing or waiting to be executed
2784      *         when this method returns; returns <code>0</code> if all jobs completed successfully
2785      *         within the timeout period
2786      * @throws IllegalArgumentException if timeoutMillis is negative
2787      * @see #waitForBackgroundJavaScriptStartingBefore(long)
2788      * @see #waitForBackgroundJavaScriptStartingBefore(long, long)
2789      */
2790     public int waitForBackgroundJavaScript(final long timeoutMillis) {
2791         int count = 0;
2792         final long endTime = System.currentTimeMillis() + timeoutMillis;
2793         for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2794             final JavaScriptJobManager jobManager;
2795             final WeakReference<JavaScriptJobManager> reference;
2796             try {
2797                 reference = i.next();
2798                 jobManager = reference.get();
2799                 if (jobManager == null) {
2800                     i.remove();
2801                     continue;
2802                 }
2803             }
2804             catch (final ConcurrentModificationException e) {
2805                 i = jobManagers_.iterator();
2806                 count = 0;
2807                 continue;
2808             }
2809 
2810             final long newTimeout = endTime - System.currentTimeMillis();
2811             count += jobManager.waitForJobs(newTimeout);
2812         }
2813         if (count != getAggregateJobCount()) {
2814             final long newTimeout = endTime - System.currentTimeMillis();
2815             return waitForBackgroundJavaScript(newTimeout);
2816         }
2817         return count;
2818     }
2819 
2820     /**
2821      * <p>Blocks until all background JavaScript tasks scheduled to start executing before
2822      * <code>(now + delayMillis)</code> have finished executing. Background JavaScript tasks include:</p>
2823      * <ul>
2824      *   <li>JavaScript scheduled via <code>window.setTimeout()</code></li>
2825      *   <li>JavaScript scheduled via <code>window.setInterval()</code></li>
2826      *   <li>Asynchronous <code>XMLHttpRequest</code> operations</li>
2827      *   <li>Other asynchronous JavaScript operations across all windows managed by this WebClient</li>
2828      * </ul>
2829      *
2830      * <p><strong>Method Behavior:</strong></p>
2831      * <ul>
2832      *   <li>If no background JavaScript tasks are currently executing and none are scheduled
2833      *       to start within <code>delayMillis</code>, this method returns immediately</li>
2834      *   <li>Tasks scheduled to execute after <code>(now + delayMillis)</code> are ignored
2835      *       and do not affect the waiting behavior</li>
2836      *   <li>The method waits for tasks to complete execution, not just to start</li>
2837      *   <li>This method waits indefinitely for qualifying tasks to complete (no timeout)</li>
2838      * </ul>
2839      *
2840      * <p><strong>Use Case:</strong> This method is ideal when you know approximately when
2841      * background JavaScript should start executing but are uncertain about execution duration.
2842      * Use this when you don't need a timeout and want to ensure all relevant tasks complete.
2843      * For scenarios where you need to wait for all background tasks regardless of timing,
2844      * use {@link #waitForBackgroundJavaScript(long)} instead. For timeout control, use
2845      * {@link #waitForBackgroundJavaScriptStartingBefore(long, long)} instead.</p>
2846      *
2847      * <p><strong>Thread Safety:</strong> This method is thread-safe and handles concurrent
2848      * modifications to the internal job manager list gracefully.</p>
2849      *
2850      * <p><strong>Example Usage:</strong></p>
2851      * <pre><code>
2852      * // Wait indefinitely for JavaScript tasks starting within 1 second
2853      * int remainingJobs = webClient.waitForBackgroundJavaScriptStartingBefore(1000);
2854      * if (remainingJobs == 0) {
2855      *     log("All relevant background JavaScript completed");
2856      * } else {
2857      *     log("Some tasks may still be pending: " + remainingJobs + " jobs");
2858      * }
2859      *
2860      * // Common pattern: wait for tasks that should start soon
2861      * // (useful after triggering an action that schedules JavaScript)
2862      * webClient.waitForBackgroundJavaScriptStartingBefore(500);
2863      * </code></pre>
2864      *
2865      * @param delayMillis the delay which determines the background tasks to wait for (in milliseconds);
2866      *                   must be non-negative
2867      * @return the number of background JavaScript jobs still executing or waiting to be executed
2868      *         when this method returns; returns <code>0</code> if all qualifying jobs completed
2869      *         successfully
2870      * @see #waitForBackgroundJavaScript(long)
2871      * @see #waitForBackgroundJavaScriptStartingBefore(long, long)
2872      */
2873     public int waitForBackgroundJavaScriptStartingBefore(final long delayMillis) {
2874         return waitForBackgroundJavaScriptStartingBefore(delayMillis, -1);
2875     }
2876 
2877     /**
2878      * <p>Blocks until all background JavaScript tasks scheduled to start executing before
2879      * <code>(now + delayMillis)</code> have finished executing, or until the specified timeout
2880      * is reached, whichever occurs first. Background JavaScript tasks include:</p>
2881      * <ul>
2882      *   <li>JavaScript scheduled via <code>window.setTimeout()</code></li>
2883      *   <li>JavaScript scheduled via <code>window.setInterval()</code></li>
2884      *   <li>Asynchronous <code>XMLHttpRequest</code> operations</li>
2885      *   <li>Other asynchronous JavaScript operations across all windows managed by this WebClient</li>
2886      * </ul>
2887      *
2888      * <p><strong>Method Behavior:</strong></p>
2889      * <ul>
2890      *   <li>If no background JavaScript tasks are currently executing and none are scheduled
2891      *       to start within <code>delayMillis</code>, this method returns immediately</li>
2892      *   <li>Tasks scheduled to execute after <code>(now + delayMillis)</code> are ignored
2893      *       and do not affect the waiting behavior</li>
2894      *   <li>The method waits for tasks to complete execution, not just to start</li>
2895      * </ul>
2896      *
2897      * <p><strong>Timeout Behavior:</strong></p>
2898      * <ul>
2899      *   <li>If <code>timeoutMillis</code> is negative or less than <code>delayMillis</code>,
2900      *       the timeout is ignored and the method waits indefinitely</li>
2901      *   <li>When a valid timeout is specified, the method will never block longer than
2902      *       <code>timeoutMillis</code> milliseconds</li>
2903      *   <li>The timeout applies to the total waiting time, not per task</li>
2904      * </ul>
2905      *
2906      * <p><strong>Use Case:</strong> This method is ideal when you know approximately when
2907      * background JavaScript should start executing but are uncertain about execution duration.
2908      * For scenarios where you need to wait for all background tasks regardless of timing,
2909      * use {@link #waitForBackgroundJavaScript(long)} instead.</p>
2910      *
2911      * <p><strong>Thread Safety:</strong> This method is thread-safe and handles concurrent
2912      * modifications to the internal job manager list gracefully.</p>
2913      *
2914      * <p><strong>Example Usage:</strong></p>
2915      * <pre><code>
2916      * // Wait for JavaScript tasks starting within 1 second, with 10 second max timeout
2917      * int remainingJobs = webClient.waitForBackgroundJavaScriptStartingBefore(1000, 10000);
2918      * if (remainingJobs == 0) {
2919      *     log("All relevant background JavaScript completed");
2920      * } else {
2921      *     log("Timeout reached or tasks still pending: " + remainingJobs + " jobs");
2922      * }
2923      *
2924      * // Wait indefinitely for tasks starting within 500ms (timeout ignored)
2925      * webClient.waitForBackgroundJavaScriptStartingBefore(500, 100); // timeout &lt; delay
2926      * </code></pre>
2927      *
2928      * @param delayMillis the delay which determines the background tasks to wait for (in milliseconds);
2929      *                   must be non-negative
2930      * @param timeoutMillis the maximum amount of time to wait (in milliseconds); if negative or
2931      *                     less than <code>delayMillis</code>, the timeout is ignored and the method
2932      *                     waits indefinitely for qualifying tasks to complete
2933      * @return the number of background JavaScript jobs still executing or waiting to be executed
2934      *         when this method returns; returns <code>0</code> if all qualifying jobs completed
2935      *         successfully within the specified constraints
2936      * @see #waitForBackgroundJavaScript(long)
2937      * @see #waitForBackgroundJavaScriptStartingBefore(long)
2938      */
2939     public int waitForBackgroundJavaScriptStartingBefore(final long delayMillis, final long timeoutMillis) {
2940         int count = 0;
2941         long now = System.currentTimeMillis();
2942         final long endTime = now + delayMillis;
2943         long endTimeout = now + timeoutMillis;
2944         if (timeoutMillis < 0 || timeoutMillis < delayMillis) {
2945             endTimeout = -1;
2946         }
2947 
2948         for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2949             final JavaScriptJobManager jobManager;
2950             final WeakReference<JavaScriptJobManager> reference;
2951             try {
2952                 reference = i.next();
2953                 jobManager = reference.get();
2954                 if (jobManager == null) {
2955                     i.remove();
2956                     continue;
2957                 }
2958             }
2959             catch (final ConcurrentModificationException e) {
2960                 i = jobManagers_.iterator();
2961                 count = 0;
2962                 continue;
2963             }
2964             now = System.currentTimeMillis();
2965             final long newDelay = endTime - now;
2966             final long newTimeout = (endTimeout == -1) ? -1 : endTimeout - now;
2967             count += jobManager.waitForJobsStartingBefore(newDelay, newTimeout);
2968         }
2969         if (count != getAggregateJobCount()) {
2970             now = System.currentTimeMillis();
2971             final long newDelay = endTime - now;
2972             final long newTimeout = (endTimeout == -1) ? -1 : endTimeout - now;
2973             return waitForBackgroundJavaScriptStartingBefore(newDelay, newTimeout);
2974         }
2975         return count;
2976     }
2977 
2978     /**
2979      * Returns the aggregate background JavaScript job count across all windows.
2980      * @return the aggregate background JavaScript job count across all windows
2981      */
2982     private int getAggregateJobCount() {
2983         int count = 0;
2984         for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2985             final JavaScriptJobManager jobManager;
2986             final WeakReference<JavaScriptJobManager> reference;
2987             try {
2988                 reference = i.next();
2989                 jobManager = reference.get();
2990                 if (jobManager == null) {
2991                     i.remove();
2992                     continue;
2993                 }
2994             }
2995             catch (final ConcurrentModificationException e) {
2996                 i = jobManagers_.iterator();
2997                 count = 0;
2998                 continue;
2999             }
3000             final int jobCount = jobManager.getJobCount();
3001             count += jobCount;
3002         }
3003         return count;
3004     }
3005 
3006     /**
3007      * When we deserialize, re-initializie transient fields.
3008      * @param in the object input stream
3009      * @throws IOException if an error occurs
3010      * @throws ClassNotFoundException if an error occurs
3011      */
3012     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
3013         in.defaultReadObject();
3014 
3015         webConnection_ = new HttpWebConnection(this);
3016         scriptEngine_ = new JavaScriptEngine(this);
3017         jobManagers_ = Collections.synchronizedList(new ArrayList<>());
3018         loadQueue_ = new ArrayList<>();
3019         css3ParserPool_ = new CSS3ParserPool();
3020         broadcastChannel_ = new HashSet<>();
3021         blobUrlStore_ = new BlobUrlStore();
3022 
3023         // the job managers are not part of the serialized state; register them again
3024         // (the event loop is started by the job manager as soon as a new job is added)
3025         for (final WebWindow window : new ArrayList<>(windows_)) {
3026             jobManagers_.add(new WeakReference<>(window.getJobManager()));
3027         }
3028     }
3029 
3030     private static class LoadJob {
3031         private final WebWindow requestingWindow_;
3032         private final String target_;
3033         private final WebResponse response_;
3034         private final WeakReference<Page> originalPage_;
3035         private final WebRequest request_;
3036         private final String forceAttachmentWithFilename_;
3037 
3038         // we can't us the WebRequest from the WebResponse because
3039         // we need the original request e.g. after a redirect
3040         LoadJob(final WebRequest request, final WebResponse response,
3041                 final WebWindow requestingWindow, final String target, final String forceAttachmentWithFilename) {
3042             request_ = request;
3043             requestingWindow_ = requestingWindow;
3044             target_ = target;
3045             response_ = response;
3046             originalPage_ = new WeakReference<>(requestingWindow.getEnclosedPage());
3047             forceAttachmentWithFilename_ = forceAttachmentWithFilename;
3048         }
3049 
3050         public boolean isOutdated() {
3051             if (target_ != null && !target_.isEmpty()) {
3052                 return false;
3053             }
3054 
3055             if (requestingWindow_.isClosed()) {
3056                 return true;
3057             }
3058 
3059             return requestingWindow_.getEnclosedPage() != originalPage_.get();
3060         }
3061     }
3062 
3063     /**
3064      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3065      *
3066      * Perform the downloads and stores it for loading later into a window.
3067      * In the future downloads should be performed in parallel in separated threads.
3068      * TODO: refactor it before next release.
3069      * @param requestingWindow the window from which the request comes
3070      * @param target the name of the target window
3071      * @param request the request to perform
3072      * @param checkHash if true check for hashChenage
3073      * @param forceAttachmentWithFilename if not {@code null} the AttachmentHandler isAttachment() method is not called,
3074      *        the response has to be handled as attachment in any case
3075      * @param description information about the origin of the request. Useful for debugging.
3076      */
3077     public void download(final WebWindow requestingWindow, final String target,
3078         final WebRequest request, final boolean checkHash,
3079         final String forceAttachmentWithFilename, final String description) {
3080 
3081         final WebWindow targetWindow = resolveWindow(requestingWindow, target, true);
3082         final URL url = request.getUrl();
3083 
3084         if (targetWindow != null && HttpMethod.POST != request.getHttpMethod()) {
3085             final Page page = targetWindow.getEnclosedPage();
3086             if (page != null) {
3087                 if (page.isHtmlPage() && !((HtmlPage) page).isOnbeforeunloadAccepted()) {
3088                     return;
3089                 }
3090 
3091                 if (checkHash) {
3092                     final URL current = page.getUrl();
3093                     final boolean justHashJump =
3094                             HttpMethod.GET == request.getHttpMethod()
3095                             && UrlUtils.sameFile(url, current)
3096                             && null != url.getRef();
3097 
3098                     if (justHashJump) {
3099                         processOnlyHashChange(targetWindow, url);
3100                         return;
3101                     }
3102                 }
3103             }
3104         }
3105 
3106         synchronized (loadQueue_) {
3107             // verify if this load job doesn't already exist
3108             for (final LoadJob otherLoadJob : loadQueue_) {
3109                 if (otherLoadJob.response_ == null) {
3110                     continue;
3111                 }
3112                 final WebRequest otherRequest = otherLoadJob.request_;
3113                 final URL otherUrl = otherRequest.getUrl();
3114 
3115                 if (url.getPath().equals(otherUrl.getPath()) // fail fast
3116                     && url.toString().equals(otherUrl.toString())
3117                     && request.getRequestParameters().equals(otherRequest.getRequestParameters())
3118                     && Objects.equals(request.getRequestBody(), otherRequest.getRequestBody())) {
3119                     return; // skip it;
3120                 }
3121             }
3122         }
3123 
3124         final LoadJob loadJob;
3125         try {
3126             WebResponse response = makeWebResponseForSrcdoc(targetWindow, request);
3127             try {
3128                 if (response == null) {
3129                     response = loadWebResponse(request);
3130                 }
3131                 if (response == null) {
3132                     // blocked by the redirect filter of the request
3133                     return;
3134                 }
3135             }
3136             catch (final NoHttpResponseException e) {
3137                 LOG.error("NoHttpResponseException while downloading; generating a NoHttpResponse", e);
3138                 response = new WebResponse(RESPONSE_DATA_NO_HTTP_RESPONSE, request, 0);
3139             }
3140             loadJob = new LoadJob(request, response, requestingWindow, target, forceAttachmentWithFilename);
3141         }
3142         catch (final IOException e) {
3143             throw new RuntimeException(e);
3144         }
3145 
3146         synchronized (loadQueue_) {
3147             loadQueue_.add(loadJob);
3148         }
3149     }
3150 
3151     /**
3152      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3153      *
3154      * Loads downloaded responses into the corresponding windows.
3155      * TODO: refactor it before next release.
3156      * @throws IOException in case of exception
3157      * @throws FailingHttpStatusCodeException in case of exception
3158      */
3159     public void loadDownloadedResponses() throws FailingHttpStatusCodeException, IOException {
3160         final List<LoadJob> queue;
3161 
3162         // synchronize access to the loadQueue_,
3163         // to be sure no job is ignored
3164         synchronized (loadQueue_) {
3165             if (loadQueue_.isEmpty()) {
3166                 return;
3167             }
3168             queue = new ArrayList<>(loadQueue_);
3169             loadQueue_.clear();
3170         }
3171 
3172         final HashSet<WebWindow> updatedWindows = new HashSet<>();
3173         for (int i = queue.size() - 1; i >= 0; --i) {
3174             final LoadJob loadJob = queue.get(i);
3175             if (loadJob.isOutdated()) {
3176                 if (LOG.isInfoEnabled()) {
3177                     LOG.info("No usage of download: " + loadJob);
3178                 }
3179                 continue;
3180             }
3181 
3182             final WebWindow window = resolveWindow(loadJob.requestingWindow_, loadJob.target_, true);
3183             if (updatedWindows.contains(window)) {
3184                 if (LOG.isInfoEnabled()) {
3185                     LOG.info("No usage of download: " + loadJob);
3186                 }
3187                 continue;
3188             }
3189 
3190             final WebWindow win = openTargetWindow(loadJob.requestingWindow_, loadJob.target_, TARGET_SELF);
3191             final Page pageBeforeLoad = win.getEnclosedPage();
3192             loadWebResponseInto(loadJob.response_, win, loadJob.forceAttachmentWithFilename_);
3193 
3194             // start execution here.
3195             if (scriptEngine_ != null) {
3196                 scriptEngine_.registerWindowAndMaybeStartEventLoop(win);
3197             }
3198 
3199             if (pageBeforeLoad != win.getEnclosedPage()) {
3200                 updatedWindows.add(win);
3201             }
3202 
3203             // check and report problems if needed
3204             throwFailingHttpStatusCodeExceptionIfNecessary(loadJob.response_);
3205         }
3206     }
3207 
3208     private static void processOnlyHashChange(final WebWindow window, final URL urlWithOnlyHashChange) {
3209         final Page page = window.getEnclosedPage();
3210         final String oldURL = page.getUrl().toExternalForm();
3211 
3212         // update request url
3213         final WebRequest req = page.getWebResponse().getWebRequest();
3214         req.setUrl(urlWithOnlyHashChange);
3215 
3216         // update location.hash
3217         final Window jsWindow = window.getScriptableObject();
3218         if (null != jsWindow) {
3219             final Location location = jsWindow.getLocation();
3220             location.setHash(oldURL, urlWithOnlyHashChange.getRef());
3221         }
3222 
3223         // add to history
3224         window.getHistory().addPage(page);
3225     }
3226 
3227     /**
3228      * Returns the options object of this WebClient.
3229      * @return the options object
3230      */
3231     public WebClientOptions getOptions() {
3232         return options_;
3233     }
3234 
3235     /**
3236      * Gets the holder for the different storages.
3237      * <p><span style="color:red">Experimental API: May be changed in next release!</span></p>
3238      * @return the holder
3239      */
3240     public StorageHolder getStorageHolder() {
3241         return storageHolder_;
3242     }
3243 
3244     /**
3245      * Returns the currently configured cookies applicable to the specified URL, in an unmodifiable set.
3246      * If disabled, this returns an empty set.
3247      * @param url the URL on which to filter the returned cookies
3248      * @return the currently configured cookies applicable to the specified URL, in an unmodifiable set
3249      */
3250     public Set<Cookie> getCookies(final URL url) {
3251         final CookieManager cookieManager = getCookieManager();
3252 
3253         if (!cookieManager.isCookiesEnabled()) {
3254             return Collections.emptySet();
3255         }
3256 
3257         final URL normalizedUrl = HttpClientConverter.replaceForCookieIfNecessary(url);
3258 
3259         final String host = normalizedUrl.getHost();
3260         // URLs like "about:blank" don't have cookies and we need to catch these
3261         // cases here before HttpClient complains
3262         if (host.isEmpty()) {
3263             return Collections.emptySet();
3264         }
3265 
3266         // discard expired cookies
3267         cookieManager.clearExpired(new Date());
3268 
3269         final Set<Cookie> matchingCookies = new LinkedHashSet<>();
3270         HttpClientConverter.addMatching(cookieManager.getCookies(), normalizedUrl,
3271                 getBrowserVersion(), matchingCookies);
3272         return Collections.unmodifiableSet(matchingCookies);
3273     }
3274 
3275     /**
3276      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3277      *
3278      * Same-site comparison per the HTML "same site" algorithm: same scheme and same
3279      * registrable domain (eTLD+1, based on the public suffix list), ignoring port and subdomain.
3280      *
3281      * @param url1 the first url
3282      * @param url2 the second url
3283      * @return whether both urls are same-site
3284      */
3285     public static boolean isSameSite(final URL url1, final URL url2) {
3286         return HttpClientConverter.isSameSite(url1, url2);
3287     }
3288 
3289     /**
3290      * Parses the given cookie and adds this to our cookie store.
3291      * The cookie is treated as set by a non-HTTP API (e.g. document.cookie);
3292      * HttpOnly cookies are ignored and existing HttpOnly cookies are not replaced.
3293      * @param cookieString the string to parse
3294      * @param pageUrl the url of the page that likes to set the cookie
3295      * @param origin the requester
3296      */
3297     public void addCookie(final String cookieString, final URL pageUrl, final Object origin) {
3298         addCookie(cookieString, pageUrl, origin, false);
3299     }
3300 
3301     /**
3302      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3303      *
3304      * Parses the given cookie and adds this to our cookie store.
3305      * The cookie is treated as set by a non-HTTP API (e.g. document.cookie);
3306      * HttpOnly cookies are ignored and existing HttpOnly cookies are not replaced.
3307      * @param cookieString the string to parse
3308      * @param pageUrl the url of the page that likes to set the cookie
3309      * @param origin the requester
3310      * @param sameSiteNoneOnly if {@code true} only 'SameSite=None' cookies are added; like the browsers,
3311      *        a document in a cross-site context (e.g. a cross-site iframe) can set only these cookies
3312      */
3313     public void addCookie(final String cookieString, final URL pageUrl, final Object origin,
3314             final boolean sameSiteNoneOnly) {
3315         final CookieManager cookieManager = getCookieManager();
3316         if (!cookieManager.isCookiesEnabled()) {
3317             if (LOG.isDebugEnabled()) {
3318                 LOG.debug("Skipped adding cookie: '" + cookieString
3319                         + "' because cookies are not enabled for the CookieManager.");
3320             }
3321             return;
3322         }
3323 
3324         try {
3325             final List<Cookie> cookies = HttpClientConverter.parseCookie(cookieString, pageUrl, getBrowserVersion());
3326             final boolean secureOrigin = HttpClientConverter.isSecureCookieOrigin(
3327                                             HttpClientConverter.buildCookieOrigin(pageUrl));
3328             // final List<Cookie> cookies = CookieParser.parseCookie(cookieString, pageUrl, getBrowserVersion());
3329 
3330             for (final Cookie cookie : cookies) {
3331                 if (sameSiteNoneOnly && !"none".equalsIgnoreCase(cookie.getSameSite())) {
3332                     continue;
3333                 }
3334 
3335                 // RFC 6265 5.3 steps 10 and 11: a non-HTTP API must neither
3336                 // create an HttpOnly cookie nor replace an existing one
3337                 if (cookie.isHttpOnly()) {
3338                     continue;
3339                 }
3340                 boolean replacesHttpOnly = false;
3341                 for (final Cookie existing : cookieManager.getCookies()) {
3342                     if (existing.isHttpOnly() && existing.equals(cookie)) {
3343                         replacesHttpOnly = true;
3344                         break;
3345                     }
3346                 }
3347                 if (replacesHttpOnly) {
3348                     continue;
3349                 }
3350 
3351                 // RFC 6265bis 5.7 step 16: an insecure origin must not overwrite (or shadow) a secure cookie
3352                 if (!secureOrigin && !cookie.isSecure()
3353                         && HttpClientConverter.shadowsSecureCookie(cookie, cookieManager.getCookies())) {
3354                     continue;
3355                 }
3356 
3357                 cookieManager.addCookie(cookie);
3358 
3359                 if (LOG.isDebugEnabled()) {
3360                     LOG.debug("Added cookie: '" + cookieString + "'");
3361                 }
3362             }
3363         }
3364         catch (final MalformedCookieException e) {
3365             if (LOG.isDebugEnabled()) {
3366                 LOG.warn("Adding cookie '" + cookieString + "' failed.", e);
3367             }
3368             getIncorrectnessListener().notify("Adding cookie '" + cookieString
3369                         + "' failed; reason: '" + e.getMessage() + "'.", origin);
3370         }
3371     }
3372 
3373     /**
3374      * Returns true if the javaScript support is enabled.
3375      * To disable the javascript support (eg. temporary)
3376      * you have to use the {@link WebClientOptions#setJavaScriptEnabled(boolean)} setter.
3377      * @see #isJavaScriptEngineEnabled()
3378      * @see WebClientOptions#isJavaScriptEnabled()
3379      * @return true if the javaScript engine and the javaScript support is enabled.
3380      */
3381     public boolean isJavaScriptEnabled() {
3382         return javaScriptEngineEnabled_ && getOptions().isJavaScriptEnabled();
3383     }
3384 
3385     /**
3386      * Returns true if the javaScript engine is enabled.
3387      * To disable the javascript engine you have to use the
3388      * {@link WebClient#WebClient(BrowserVersion, boolean, String, int)} constructor.
3389      * @return true if the javaScript engine is enabled.
3390      */
3391     public boolean isJavaScriptEngineEnabled() {
3392         return javaScriptEngineEnabled_;
3393     }
3394 
3395     /**
3396      * Parses the given XHtml code string and loads the resulting XHtmlPage into
3397      * the current window.
3398      *
3399      * @param htmlCode the html code as string
3400      * @return the HtmlPage
3401      * @throws IOException in case of error
3402      */
3403     public HtmlPage loadHtmlCodeIntoCurrentWindow(final String htmlCode) throws IOException {
3404         final HTMLParser htmlParser = getPageCreator().getHtmlParser();
3405         final WebWindow webWindow = getCurrentWindow();
3406 
3407         final StringWebResponse webResponse =
3408                 new StringWebResponse(htmlCode, new URL("https://www.htmlunit.org/dummy.html"));
3409         final HtmlPage page = new HtmlPage(webResponse, webWindow);
3410         webWindow.setEnclosedPage(page);
3411 
3412         htmlParser.parse(this, webResponse, page, false, false);
3413         return page;
3414     }
3415 
3416     /**
3417      * Parses the given XHtml code string and loads the resulting XHtmlPage into
3418      * the current window.
3419      *
3420      * @param xhtmlCode the xhtml code as string
3421      * @return the XHtmlPage
3422      * @throws IOException in case of error
3423      */
3424     public XHtmlPage loadXHtmlCodeIntoCurrentWindow(final String xhtmlCode) throws IOException {
3425         final HTMLParser htmlParser = getPageCreator().getHtmlParser();
3426         final WebWindow webWindow = getCurrentWindow();
3427 
3428         final StringWebResponse webResponse =
3429                 new StringWebResponse(xhtmlCode, new URL("https://www.htmlunit.org/dummy.html"));
3430         final XHtmlPage page = new XHtmlPage(webResponse, webWindow);
3431         webWindow.setEnclosedPage(page);
3432 
3433         htmlParser.parse(this, webResponse, page, true, false);
3434         return page;
3435     }
3436 
3437     /**
3438      * Creates a new {@link WebSocketAdapter}.
3439      *
3440      * @param webSocketListener the {@link WebSocketListener}
3441      * @return a new {@link WebSocketAdapter}
3442      */
3443     public WebSocketAdapter buildWebSocketAdapter(final WebSocketListener webSocketListener) {
3444         return webSocketAdapterFactory_.buildWebSocketAdapter(this, webSocketListener);
3445     }
3446 
3447     /**
3448      * Defines a new factory method to create a new WebSocketAdapter.
3449      *
3450      * @param factory a {@link WebSocketAdapterFactory}
3451      */
3452     public void setWebSocketAdapter(final WebSocketAdapterFactory factory) {
3453         webSocketAdapterFactory_ = factory;
3454     }
3455 
3456     /**
3457      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3458      *
3459      * @return a CSS3Parser that will return to an internal pool for reuse if closed using the
3460      *         try-with-resource concept
3461      */
3462     public PooledCSS3Parser getCSS3Parser() {
3463         return this.css3ParserPool_.get();
3464     }
3465 
3466     /**
3467      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3468      *
3469      * @return the set of known {@link BroadcastChannel}s
3470      */
3471     public Set<BroadcastChannel> getBroadcastChannels() {
3472         return broadcastChannel_;
3473     }
3474 
3475     /**
3476      * Our pool of CSS3Parsers. If you need a parser, get it from here and use the AutoCloseable
3477      * functionality with a try-with-resource block. If you don't want to do that at all, continue
3478      * to build CSS3Parsers the old fashioned way.
3479      * <p>
3480      * Fetching a parser is thread safe. This API is built to minimize synchronization overhead,
3481      * hence it is possible to miss a returned parser from another thread under heavy pressure,
3482      * but because that is unlikely, we keep it simple and efficient. Caches are not supposed
3483      * to give cutting-edge guarantees.
3484      * </p>
3485      * <p>
3486      * This concept avoids a resource leak when someone does not close the fetched
3487      * parser because the pool does not know anything about the parser unless
3488      * it returns. We are not running a checkout-checkin concept.
3489      * </p>
3490      * <p>
3491      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3492      * </p>
3493      */
3494     static class CSS3ParserPool {
3495         /*
3496          * Our pool. We only hold data when it is available. In addition, synchronization against
3497          * this deque is cheap.
3498          */
3499         private final ConcurrentLinkedDeque<PooledCSS3Parser> parsers_ = new ConcurrentLinkedDeque<>();
3500 
3501         /**
3502          * Fetch a new or recycled CSS3parser. Make sure you use the try-with-resource concept
3503          * to automatically return it after use because a parser creation is expensive.
3504          * We won't get a leak, if you don't do so, but that will remove the advantage.
3505          *
3506          * @return a parser
3507          */
3508         public PooledCSS3Parser get() {
3509             // see if we have one, LIFO
3510             final PooledCSS3Parser parser = parsers_.pollLast();
3511 
3512             // if we don't have one, get us one
3513             return parser != null ? parser.markInUse(this) : new PooledCSS3Parser(this);
3514         }
3515 
3516         /**
3517          * Return a parser. Normally you don't have to use that method explicitly.
3518          * Prefer to user the AutoCloseable interface of the PooledParser by
3519          * using a try-with-resource statement.
3520          *
3521          * @param parser the parser to recycle
3522          */
3523         protected void recycle(final PooledCSS3Parser parser) {
3524             parsers_.addLast(parser);
3525         }
3526     }
3527 
3528     /**
3529      * This is a poolable CSS3Parser which can be reused automatically when closed.
3530      * A regular CSS3Parser is not thread-safe, hence also our pooled parser
3531      * is not thread-safe.
3532      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
3533      */
3534     public static class PooledCSS3Parser extends CSS3Parser implements AutoCloseable {
3535         /**
3536          * The pool we want to return us to. Because multiple threads can use this, we
3537          * have to ensure that we see the action here.
3538          */
3539         private CSS3ParserPool pool_;
3540 
3541         /**
3542          * Create a new poolable parser.
3543          *
3544          * @param pool the pool the parser should return to when it is closed
3545          */
3546         protected PooledCSS3Parser(final CSS3ParserPool pool) {
3547             super();
3548             this.pool_ = pool;
3549         }
3550 
3551         /**
3552          * Resets the parser's pool state so it can be safely returned again.
3553          *
3554          * @param pool the pool the parser should return to when it is closed
3555          * @return this parser for fluid programming
3556          */
3557         protected PooledCSS3Parser markInUse(final CSS3ParserPool pool) {
3558             // ensure we detect programming mistakes
3559             if (this.pool_ == null) {
3560                 this.pool_ = pool;
3561             }
3562             else {
3563                 throw new IllegalStateException("This PooledParser was not returned to the pool properly");
3564             }
3565 
3566             return this;
3567         }
3568 
3569         /**
3570          * Implements the AutoClosable interface. The return method ensures that
3571          * we are notified when we incorrectly close it twice which indicates a
3572          * programming flow defect.
3573          *
3574          * @throws IllegalStateException in case the parser is closed several times
3575          */
3576         @Override
3577         public void close() {
3578             if (this.pool_ != null) {
3579                 final CSS3ParserPool oldPool = this.pool_;
3580                 // set null first and recycle later to avoid exposing a broken state
3581                 // volatile guarantees visibility
3582                 this.pool_ = null;
3583 
3584                 // return
3585                 oldPool.recycle(this);
3586             }
3587             else {
3588                 throw new IllegalStateException("This PooledParser was returned already");
3589             }
3590         }
3591     }
3592 }