View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import static org.htmlunit.BrowserVersionFeatures.CSP_FORM_ACTION_REDIRECTS_NOT_CHECKED;
18  import static org.htmlunit.BrowserVersionFeatures.FORM_IGNORE_REL_NOREFERRER;
19  import static org.htmlunit.BrowserVersionFeatures.FORM_SUBMISSION_HEADER_CACHE_CONTROL_MAX_AGE;
20  
21  import java.net.MalformedURLException;
22  import java.net.URL;
23  import java.nio.charset.Charset;
24  import java.nio.charset.StandardCharsets;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Collection;
28  import java.util.HashMap;
29  import java.util.HashSet;
30  import java.util.List;
31  import java.util.Locale;
32  import java.util.Map;
33  import java.util.Objects;
34  import java.util.function.Predicate;
35  import java.util.regex.Pattern;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.htmlunit.BrowserVersion;
40  import org.htmlunit.ElementNotFoundException;
41  import org.htmlunit.FormEncodingType;
42  import org.htmlunit.HttpHeader;
43  import org.htmlunit.HttpMethod;
44  import org.htmlunit.Page;
45  import org.htmlunit.ScriptResult;
46  import org.htmlunit.SgmlPage;
47  import org.htmlunit.WebAssert;
48  import org.htmlunit.WebClient;
49  import org.htmlunit.WebRequest;
50  import org.htmlunit.WebWindow;
51  import org.htmlunit.html.csp.ContentSecurityPolicy;
52  import org.htmlunit.http.HttpUtils;
53  import org.htmlunit.javascript.host.event.Event;
54  import org.htmlunit.javascript.host.event.SubmitEvent;
55  import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
56  import org.htmlunit.util.ArrayUtils;
57  import org.htmlunit.util.EncodingSniffer;
58  import org.htmlunit.util.NameValuePair;
59  import org.htmlunit.util.StringUtils;
60  import org.htmlunit.util.UrlUtils;
61  
62  /**
63   * Wrapper for the HTML element "form".
64   *
65   * @author Mike Bowler
66   * @author David K. Taylor
67   * @author Brad Clarke
68   * @author Christian Sell
69   * @author Marc Guillemot
70   * @author George Murnock
71   * @author Kent Tong
72   * @author Ahmed Ashour
73   * @author Philip Graf
74   * @author Ronald Brill
75   * @author Frank Danek
76   * @author Anton Demydenko
77   * @author Lai Quang Duong
78   */
79  public class HtmlForm extends HtmlElement {
80      private static final Log LOG = LogFactory.getLog(HtmlForm.class);
81  
82      /** The HTML tag represented by this element. */
83      public static final String TAG_NAME = "form";
84  
85      /** The "novalidate" attribute name. */
86      private static final String ATTRIBUTE_NOVALIDATE = "novalidate";
87  
88      /** The "formnovalidate" attribute name. */
89      public static final String ATTRIBUTE_FORMNOVALIDATE = "formnovalidate";
90  
91      private static final HashSet<String> SUBMITTABLE_TAG_NAMES = new HashSet<>(Arrays.asList(HtmlInput.TAG_NAME,
92          HtmlButton.TAG_NAME, HtmlSelect.TAG_NAME, HtmlTextArea.TAG_NAME));
93  
94      private static final Pattern SUBMIT_CHARSET_PATTERN = Pattern.compile("[ ,].*");
95  
96      private boolean isPreventDefault_;
97  
98      /**
99       * A map that holds past names (name or id attribute) to elements belonging to this form.
100      * @see <a href="https://html.spec.whatwg.org/multipage/forms.html#the-form-element:the-form-element-10">
101      *     HTML spec - past names map</a>
102      */
103     private Map<String, HtmlElement> pastNamesMap_;
104 
105     /**
106      * Creates an instance.
107      *
108      * @param qualifiedName the qualified name of the element type to instantiate
109      * @param htmlPage the page that contains this element
110      * @param attributes the initial attributes
111      */
112     HtmlForm(final String qualifiedName, final SgmlPage htmlPage,
113             final Map<String, DomAttr> attributes) {
114         super(qualifiedName, htmlPage, attributes);
115     }
116 
117     /**
118      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
119      *
120      * <p>Submits this form to the server. If <code>submitElement</code> is {@code null}, then
121      * the submission is treated as if it was triggered by JavaScript, and the <code>onsubmit</code>
122      * handler will not be executed.</p>
123      *
124      * <p><b>IMPORTANT:</b> Using this method directly is not the preferred way of submitting forms.
125      * Most consumers should emulate the user's actions instead, probably by using something like
126      * {@link HtmlElement#click()} or {@link HtmlElement#dblClick()}.</p>
127      *
128      * @param submitElement the element that caused the submit to occur
129      */
130     public void submit(final SubmittableElement submitElement) {
131         final HtmlPage htmlPage = (HtmlPage) getPage();
132         if (!htmlPage.isSandboxAllowed("allow-forms")) {
133             // a sandboxed document without 'allow-forms' does not submit forms
134             if (LOG.isDebugEnabled()) {
135                 LOG.debug("Form submission blocked because the document is sandboxed.");
136             }
137             return;
138         }
139         final WebClient webClient = htmlPage.getWebClient();
140 
141         if (webClient.isJavaScriptEnabled()) {
142             if (submitElement != null) {
143                 isPreventDefault_ = false;
144 
145                 boolean validate = true;
146                 if (submitElement instanceof HtmlSubmitInput input
147                         && input.isFormNoValidate()) {
148                     validate = false;
149                 }
150                 else if (submitElement instanceof HtmlButton htmlButton) {
151                     if ("submit".equalsIgnoreCase(htmlButton.getType())
152                             && htmlButton.isFormNoValidate()) {
153                         validate = false;
154                     }
155                 }
156 
157                 if (validate
158                         && getAttributeDirect(ATTRIBUTE_NOVALIDATE) != ATTRIBUTE_NOT_DEFINED) {
159                     validate = false;
160                 }
161 
162                 if (validate && !areChildrenValid()) {
163                     return;
164                 }
165                 final ScriptResult scriptResult = fireEvent(new SubmitEvent(this,
166                         ((HtmlElement) submitElement).getScriptableObject()));
167                 if (isPreventDefault_) {
168                     // null means 'nothing executed'
169                     if (scriptResult == null) {
170                         return;
171                     }
172                     return;
173                 }
174             }
175 
176             final String action = getActionAttribute().trim();
177             if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
178                 // form-action is checked before the script-src check of the javascript url
179                 final URL actionUrl = UrlUtils.toUrlSafe(action);
180                 if (ContentSecurityPolicy.allowsFormAction(htmlPage, actionUrl, actionUrl)
181                         && ContentSecurityPolicy.allowsJavaScriptUrl(htmlPage, this, action)) {
182                     htmlPage.executeJavaScript(action, "Form action", getStartLineNumber());
183                 }
184                 return;
185             }
186         }
187         else {
188             if (StringUtils.startsWithIgnoreCase(getActionAttribute(), JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
189                 // The action is JavaScript but JavaScript isn't enabled.
190                 return;
191             }
192         }
193 
194         // html5 attribute's support
195         if (submitElement != null) {
196             updateHtml5Attributes(submitElement);
197         }
198 
199         // dialog support
200         final String methodAttribute = getMethodAttribute();
201         if ("dialog".equalsIgnoreCase(methodAttribute)) {
202             // find parent dialog
203             final HtmlElement dialog = getEnclosingElement("dialog");
204             if (dialog != null) {
205                 ((HtmlDialog) dialog).close("");
206             }
207             return;
208         }
209 
210         final WebRequest request = getWebRequest(submitElement);
211         // upgrade-insecure-requests of the Content-Security-Policy
212         request.setUrl(ContentSecurityPolicy.upgradeInsecureRequest(htmlPage, request.getUrl()));
213         final URL url = request.getUrl();
214         // accessing to local resource is forbidden for security reason
215         if (!htmlPage.isLocalResourceAccessAllowed(url)) {
216             notifyIncorrectness("Not allowed to load local resource: " + url);
217             return;
218         }
219         if (!ContentSecurityPolicy.allowsFormAction(htmlPage, url, url)) {
220             return;
221         }
222         // redirects are upgraded also; Chrome checks the redirects (the url of the form submission
223         // is reported), Firefox does not
224         ContentSecurityPolicy.upgradeInsecureRedirects(htmlPage, request);
225         if (!htmlPage.getWebClient().getBrowserVersion().hasFeature(CSP_FORM_ACTION_REDIRECTS_NOT_CHECKED)) {
226             request.setRedirectFilter(
227                     redirectUrl -> ContentSecurityPolicy.allowsFormAction(htmlPage, redirectUrl, url));
228         }
229         final String target = htmlPage.getResolvedTarget(getTargetAttribute());
230 
231         final WebWindow webWindow = htmlPage.getEnclosingWindow();
232         // Calling form.submit() twice forces double download.
233         webClient.download(webWindow, target, request, false, null, "JS form.submit()");
234     }
235 
236     /**
237      * Check if element which cause submit contains new html5 attributes
238      * (formaction, formmethod, formtarget, formenctype)
239      * and override existing values.
240      * @param submitElement the element to update
241      */
242     private void updateHtml5Attributes(final SubmittableElement submitElement) {
243         if (submitElement instanceof HtmlElement element) {
244 
245             final String type = element.getAttributeDirect(TYPE_ATTRIBUTE);
246             boolean typeImage = false;
247             final boolean isInput = HtmlInput.TAG_NAME.equals(element.getTagName());
248             if (isInput) {
249                 typeImage = "image".equalsIgnoreCase(type);
250             }
251 
252             // could be excessive validation but support of html5 fromxxx
253             // attributes available for:
254             // - input with 'submit' and 'image' types
255             // - button with 'submit' or without type
256             final boolean typeSubmit = "submit".equalsIgnoreCase(type);
257             if (isInput && !typeSubmit && !typeImage) {
258                 return;
259             }
260             else if (HtmlButton.TAG_NAME.equals(element.getTagName())
261                 && !"submit".equals(((HtmlButton) element).getType())) {
262                 return;
263             }
264 
265             final String formaction = element.getAttributeDirect("formaction");
266             if (ATTRIBUTE_NOT_DEFINED != formaction) {
267                 setActionAttribute(formaction);
268             }
269             final String formmethod = element.getAttributeDirect("formmethod");
270             if (ATTRIBUTE_NOT_DEFINED != formmethod) {
271                 setMethodAttribute(formmethod);
272             }
273             final String formtarget = element.getAttributeDirect("formtarget");
274             if (ATTRIBUTE_NOT_DEFINED != formtarget) {
275                 setTargetAttribute(formtarget);
276             }
277             final String formenctype = element.getAttributeDirect("formenctype");
278             if (ATTRIBUTE_NOT_DEFINED != formenctype) {
279                 setEnctypeAttribute(formenctype);
280             }
281         }
282     }
283 
284     private boolean areChildrenValid() {
285         boolean valid = true;
286         for (final HtmlElement element : getElements(htmlElement -> htmlElement instanceof HtmlInput)) {
287             if (!element.isValid()) {
288                 if (LOG.isInfoEnabled()) {
289                     LOG.info("Form validation failed; element '" + element + "' was not valid. Submit cancelled.");
290                 }
291                 valid = false;
292                 break;
293             }
294         }
295         return valid;
296     }
297 
298     /**
299      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
300      *
301      * Gets the request for a submission of this form with the specified SubmittableElement.
302      * @param submitElement the element that caused the submit to occur
303      * @return the request
304      */
305     public WebRequest getWebRequest(final SubmittableElement submitElement) {
306         final HttpMethod method;
307         final String methodAttribute = getMethodAttribute();
308         if ("post".equalsIgnoreCase(methodAttribute)) {
309             method = HttpMethod.POST;
310         }
311         else {
312             if (!"get".equalsIgnoreCase(methodAttribute) && StringUtils.isNotBlank(methodAttribute)) {
313                 notifyIncorrectness("Incorrect submit method >" + getMethodAttribute() + "<. Using >GET<.");
314             }
315             method = HttpMethod.GET;
316         }
317 
318         String actionUrl = getActionAttribute();
319         String anchor = null;
320         String queryFormFields = "";
321         Charset enc = getSubmitCharset();
322         if (StandardCharsets.UTF_16 == enc
323                 || StandardCharsets.UTF_16BE == enc
324                 || StandardCharsets.UTF_16LE == enc) {
325             enc = StandardCharsets.UTF_8;
326         }
327 
328         final List<NameValuePair> parameters = getParameterListForSubmit(submitElement);
329         if (HttpMethod.GET == method) {
330             if (actionUrl.contains("#")) {
331                 anchor = StringUtils.substringAfter(actionUrl, "#");
332             }
333             queryFormFields = HttpUtils.toQueryFormFields(parameters, enc);
334 
335             // action may already contain some query parameters: they have to be removed
336             actionUrl = StringUtils.substringBefore(actionUrl, "#");
337             actionUrl = StringUtils.substringBefore(actionUrl, "?");
338             parameters.clear(); // parameters have been added to query
339         }
340 
341         final HtmlPage htmlPage = (HtmlPage) getPage();
342         URL url;
343         try {
344             if (actionUrl.isEmpty()) {
345                 url = WebClient.expandUrl(htmlPage.getUrl(), actionUrl);
346             }
347             else {
348                 url = htmlPage.getFullyQualifiedUrl(actionUrl);
349             }
350 
351             if (!queryFormFields.isEmpty()) {
352                 url = UrlUtils.getUrlWithNewQuery(url, queryFormFields);
353             }
354 
355             if (anchor != null && UrlUtils.URL_ABOUT_BLANK != url) {
356                 url = UrlUtils.getUrlWithNewRef(url, anchor);
357             }
358         }
359         catch (final MalformedURLException e) {
360             throw new IllegalArgumentException("Not a valid url: " + actionUrl, e);
361         }
362 
363         final BrowserVersion browser = htmlPage.getWebClient().getBrowserVersion();
364         final WebRequest request = new WebRequest(url, browser.getHtmlAcceptHeader(),
365                                                         browser.getAcceptEncodingHeader());
366         request.setHttpMethod(method);
367         request.setRequestParameters(parameters);
368         if (HttpMethod.POST == method) {
369             request.setEncodingType(FormEncodingType.getInstance(getEnctypeAttribute()));
370 
371             if (browser.hasFeature(FORM_SUBMISSION_HEADER_CACHE_CONTROL_MAX_AGE)) {
372                 request.setAdditionalHeader(HttpHeader.CACHE_CONTROL, "max-age=0");
373             }
374 
375             try {
376                 request.setAdditionalHeader(HttpHeader.ORIGIN,
377                         UrlUtils.getUrlWithProtocolAndAuthority(htmlPage.getUrl()).toExternalForm());
378             }
379             catch (final MalformedURLException e) {
380                 if (LOG.isInfoEnabled()) {
381                     LOG.info("Invalid origin url '" + htmlPage.getUrl() + "'");
382                 }
383             }
384         }
385         request.setCharset(enc);
386 
387         // Sec-Fetch-* support (https://www.w3.org/TR/fetch-metadata/):
388         // a form submission is a top-level navigation, initiated by the page
389         // containing the form. The initiator must be set regardless of
390         // "noreferrer", since Sec-Fetch-Site reflects the true relationship
391         // between initiator and target even when the Referer header itself is
392         // suppressed. Unlike anchor clicks, this method actually knows whether
393         // the submission was caused by a real submit control (submitElement != null,
394         // e.g. a click on a submit button/input) or triggered purely by script
395         // (submitElement == null, e.g. form.submit()) - see this method's javadoc -
396         // so Sec-Fetch-User can be set correctly rather than hardcoded.
397         request.markAsNavigation(htmlPage.getUrl(), submitElement != null);
398 
399         // forms are ignoring the rel='noreferrer'
400         if (browser.hasFeature(FORM_IGNORE_REL_NOREFERRER) || !relContainsNoreferrer()) {
401             request.setRefererHeader(htmlPage.getUrl());
402             request.setReferrerPolicy(htmlPage.getReferrerPolicy());
403         }
404 
405         return request;
406     }
407 
408     private boolean relContainsNoreferrer() {
409         String rel = getRelAttribute();
410         if (rel != null) {
411             rel = rel.toLowerCase(Locale.ROOT);
412             return ArrayUtils.contains(StringUtils.splitAtBlank(rel), "noreferrer");
413         }
414         return false;
415     }
416 
417     /**
418      * Returns the charset to use for the form submission. This is the first one
419      * from the list provided in {@link #getAcceptCharsetAttribute()} if any
420      * or the page's charset else
421      * @return the charset to use for the form submission
422      */
423     private Charset getSubmitCharset() {
424         String charset = getAcceptCharsetAttribute();
425         if (!charset.isEmpty()) {
426             charset = charset.trim();
427             return EncodingSniffer.toCharset(
428                     SUBMIT_CHARSET_PATTERN.matcher(charset).replaceAll("").toUpperCase(Locale.ROOT));
429         }
430         return getPage().getCharset();
431     }
432 
433     /**
434      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
435      *
436      * Returns a list of {@link NameValuePair}s that represent the data that will be
437      * sent to the server when this form is submitted. This is primarily intended to aid
438      * debugging.
439      *
440      * @param submitElement the element used to submit the form, or {@code null} if the
441      *        form was submitted by JavaScript
442      * @return the list of {@link NameValuePair}s that represent that data that will be sent
443      *         to the server when this form is submitted
444      */
445     public List<NameValuePair> getParameterListForSubmit(final SubmittableElement submitElement) {
446         final Collection<SubmittableElement> submittableElements = getSubmittableElements(submitElement);
447 
448         final List<NameValuePair> parameterList = new ArrayList<>(submittableElements.size());
449         for (final SubmittableElement element : submittableElements) {
450             parameterList.addAll(Arrays.asList(element.getSubmitNameValuePairs()));
451         }
452 
453         return parameterList;
454     }
455 
456     /**
457      * Resets this form to its initial values, returning the page contained by this form's window after the
458      * reset. Note that the returned page may or may not be the same as the original page, based on JavaScript
459      * event handlers, etc.
460      *
461      * @return the page contained by this form's window after the reset
462      */
463     public Page reset() {
464         final SgmlPage sgmlPage = getPage();
465         final ScriptResult scriptResult = fireEvent(Event.TYPE_RESET);
466         if (ScriptResult.isFalse(scriptResult)) {
467             return sgmlPage.getWebClient().getCurrentWindow().getEnclosedPage();
468         }
469 
470         for (final HtmlElement next : getHtmlElementDescendants()) {
471             if (next instanceof SubmittableElement element) {
472                 element.reset();
473             }
474         }
475 
476         return sgmlPage;
477     }
478 
479     /**
480      * {@inheritDoc}
481      */
482     @Override
483     public boolean isValid() {
484         for (final HtmlElement element : getFormElements()) {
485             if (!element.isValid()) {
486                 return false;
487             }
488         }
489         return super.isValid();
490     }
491 
492     /**
493      * Returns a collection of elements that represent all the "submittable" elements in this form,
494      * assuming that the specified element is used to submit the form.
495      *
496      * @param submitElement the element used to submit the form, or {@code null} if the
497      *        form is submitted by JavaScript
498      * @return a collection of elements that represent all the "submittable" elements in this form
499      */
500     Collection<SubmittableElement> getSubmittableElements(final SubmittableElement submitElement) {
501         final List<SubmittableElement> submittableElements = new ArrayList<>();
502 
503         for (final HtmlElement element : getElements(htmlElement -> isSubmittable(htmlElement, submitElement))) {
504             submittableElements.add((SubmittableElement) element);
505         }
506 
507         return submittableElements;
508     }
509 
510     private static boolean isValidForSubmission(final HtmlElement element, final SubmittableElement submitElement) {
511         final String tagName = element.getTagName();
512         if (!SUBMITTABLE_TAG_NAMES.contains(tagName)) {
513             return false;
514         }
515         if (element.isDisabledElementAndDisabled()) {
516             return false;
517         }
518         // clicked input type="image" is submitted even if it hasn't a name
519         if (element == submitElement && element instanceof HtmlImageInput) {
520             return true;
521         }
522 
523         if (!element.hasAttribute(NAME_ATTRIBUTE)) {
524             return false;
525         }
526 
527         if (StringUtils.isEmptyString(element.getAttributeDirect(NAME_ATTRIBUTE))) {
528             return false;
529         }
530 
531         if (element instanceof HtmlInput input) {
532             if (input.isCheckable()) {
533                 return input.isChecked();
534             }
535         }
536         if (element instanceof HtmlSelect select) {
537             return select.isValidForSubmission();
538         }
539         return true;
540     }
541 
542     /**
543      * Returns {@code true} if the specified element gets submitted when this form is submitted,
544      * assuming that the form is submitted using the specified submit element.
545      *
546      * @param element the element to check
547      * @param submitElement the element used to submit the form, or {@code null} if the form is
548      *        submitted by JavaScript
549      * @return {@code true} if the specified element gets submitted when this form is submitted
550      */
551     private static boolean isSubmittable(final HtmlElement element, final SubmittableElement submitElement) {
552         if (!isValidForSubmission(element, submitElement)) {
553             return false;
554         }
555 
556         // The one submit button that was clicked can be submitted but no other ones
557         if (element == submitElement) {
558             return true;
559         }
560         if (element instanceof HtmlInput input) {
561             if (!input.isSubmitable()) {
562                 return false;
563             }
564         }
565 
566         return !HtmlButton.TAG_NAME.equals(element.getTagName());
567     }
568 
569     /**
570      * Returns all input elements which are members of this form and have the specified name.
571      *
572      * @param name the input name to search for
573      * @return all input elements which are members of this form and have the specified name
574      */
575     public List<HtmlInput> getInputsByName(final String name) {
576         return getFormElementsByAttribute(HtmlInput.TAG_NAME, NAME_ATTRIBUTE, name);
577     }
578 
579     /**
580      * Same as {@link #getElementsByAttribute(String, String, String)} but
581      * ignoring elements that are contained in a nested form.
582      */
583     @SuppressWarnings("unchecked")
584     private <E extends HtmlElement> List<E> getFormElementsByAttribute(
585             final String elementName,
586             final String attributeName,
587             final String attributeValue) {
588 
589         return (List<E>) getElements(htmlElement ->
590                                 htmlElement.getTagName().equals(elementName)
591                                 && htmlElement.getAttribute(attributeName).equals(attributeValue));
592     }
593 
594     /**
595      * Returns the form controls contained in this form.
596      *
597      * @return a list containing all form controls in tree order (preorder,
598      *         depth-first traversal). Only the following elements are
599      *         included: {@code button}, {@code fieldset}, {@code input},
600      *         {@code object}, {@code output}, {@code select}, and
601      *         {@code textarea}
602      */
603     public List<HtmlElement> getFormElements() {
604         return getElements(htmlElement -> {
605             final String tagName = htmlElement.getTagName();
606             return HtmlButton.TAG_NAME.equals(tagName)
607                     || HtmlFieldSet.TAG_NAME.equals(tagName)
608                     || HtmlInput.TAG_NAME.equals(tagName)
609                     || HtmlObject.TAG_NAME.equals(tagName)
610                     || HtmlOutput.TAG_NAME.equals(tagName)
611                     || HtmlSelect.TAG_NAME.equals(tagName)
612                     || HtmlTextArea.TAG_NAME.equals(tagName);
613         });
614     }
615 
616     /**
617      * This is the backend for the getElements() javascript function of the form.
618      * see https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
619      *
620      * @return A List containing all non-image controls in the form.
621      *         The form controls in the returned collection are in the same order
622      *         in which they appear in the form by following a preorder,
623      *         depth-first traversal of the tree. This is called tree order.
624      *         Only the following elements are returned:
625      *         button, fieldset,
626      *         input (with the exception that any whose type is "image" are omitted for historical reasons),
627      *         object, output, select, textarea.
628      */
629     public List<HtmlElement> getElementsJS() {
630         return getElements(htmlElement -> {
631             final String tagName = htmlElement.getTagName();
632             if (HtmlInput.TAG_NAME.equals(tagName)) {
633                 return !(htmlElement instanceof HtmlImageInput);
634             }
635 
636             return HtmlButton.TAG_NAME.equals(tagName)
637                     || HtmlFieldSet.TAG_NAME.equals(tagName)
638                     || HtmlObject.TAG_NAME.equals(tagName)
639                     || HtmlOutput.TAG_NAME.equals(tagName)
640                     || HtmlSelect.TAG_NAME.equals(tagName)
641                     || HtmlTextArea.TAG_NAME.equals(tagName);
642         });
643     }
644 
645     /**
646      * Returns the form elements that match the specified filter.
647      *
648      * @param filter the predicate used to select elements
649      * @return a list of form elements matching the specified filter
650      */
651     public List<HtmlElement> getElements(final Predicate<HtmlElement> filter) {
652         final List<HtmlElement> elements = new ArrayList<>();
653 
654         if (isAttachedToPage()) {
655             for (final HtmlElement element : getPage().getDocumentElement().getHtmlElementDescendants()) {
656                 if (filter.test(element)
657                         && element.getEnclosingForm() == this) {
658                     elements.add(element);
659                 }
660             }
661         }
662         else {
663             for (final HtmlElement element : getHtmlElementDescendants()) {
664                 if (filter.test(element)) {
665                     elements.add(element);
666                 }
667             }
668         }
669 
670         return elements;
671     }
672 
673     /**
674      * Returns the first input element which is a member of this form and has the specified name.
675      *
676      * @param name the input name to search for
677      * @param <I> the input type
678      * @return the first input element which is a member of this form and has the specified name
679      * @throws ElementNotFoundException if there is no input in this form with the specified name
680      */
681     @SuppressWarnings("unchecked")
682     public final <I extends HtmlInput> I getInputByName(final String name) throws ElementNotFoundException {
683         final List<HtmlInput> inputs = getInputsByName(name);
684 
685         if (inputs.isEmpty()) {
686             throw new ElementNotFoundException(HtmlInput.TAG_NAME, NAME_ATTRIBUTE, name);
687         }
688         return (I) inputs.get(0);
689     }
690 
691     /**
692      * Returns all the {@link HtmlSelect} elements in this form that have the specified name.
693      *
694      * @param name the name to search for
695      * @return all the {@link HtmlSelect} elements in this form that have the specified name
696      */
697     public List<HtmlSelect> getSelectsByName(final String name) {
698         return getFormElementsByAttribute(HtmlSelect.TAG_NAME, NAME_ATTRIBUTE, name);
699     }
700 
701     /**
702      * Returns the first {@link HtmlSelect} element in this form that has the specified name.
703      *
704      * @param name the name to search for
705      * @return the first {@link HtmlSelect} element in this form that has the specified name
706      * @throws ElementNotFoundException if this form does not contain a {@link HtmlSelect}
707      *         element with the specified name
708      */
709     public HtmlSelect getSelectByName(final String name) throws ElementNotFoundException {
710         final List<HtmlSelect> list = getSelectsByName(name);
711         if (list.isEmpty()) {
712             throw new ElementNotFoundException(HtmlSelect.TAG_NAME, NAME_ATTRIBUTE, name);
713         }
714         return list.get(0);
715     }
716 
717     /**
718      * Returns all the {@link HtmlButton} elements in this form that have the specified name.
719      *
720      * @param name the name to search for
721      * @return all the {@link HtmlButton} elements in this form that have the specified name
722      */
723     public List<HtmlButton> getButtonsByName(final String name) {
724         return getFormElementsByAttribute(HtmlButton.TAG_NAME, NAME_ATTRIBUTE, name);
725     }
726 
727     /**
728      * Returns the first {@link HtmlButton} element in this form that has the specified name.
729      *
730      * @param name the name to search for
731      * @return the first {@link HtmlButton} element in this form that has the specified name
732      * @throws ElementNotFoundException if this form does not contain a {@link HtmlButton}
733      *         element with the specified name
734      */
735     public HtmlButton getButtonByName(final String name) throws ElementNotFoundException {
736         final List<HtmlButton> list = getButtonsByName(name);
737         if (list.isEmpty()) {
738             throw new ElementNotFoundException(HtmlButton.TAG_NAME, NAME_ATTRIBUTE, name);
739         }
740         return list.get(0);
741     }
742 
743     /**
744      * Returns all the {@link HtmlTextArea} elements in this form that have the specified name.
745      *
746      * @param name the name to search for
747      * @return all the {@link HtmlTextArea} elements in this form that have the specified name
748      */
749     public List<HtmlTextArea> getTextAreasByName(final String name) {
750         return getFormElementsByAttribute(HtmlTextArea.TAG_NAME, NAME_ATTRIBUTE, name);
751     }
752 
753     /**
754      * Returns the first {@link HtmlTextArea} element in this form that has the specified name.
755      *
756      * @param name the name to search for
757      * @return the first {@link HtmlTextArea} element in this form that has the specified name
758      * @throws ElementNotFoundException if this form does not contain a {@link HtmlTextArea}
759      *         element with the specified name
760      */
761     public HtmlTextArea getTextAreaByName(final String name) throws ElementNotFoundException {
762         final List<HtmlTextArea> list = getTextAreasByName(name);
763         if (list.isEmpty()) {
764             throw new ElementNotFoundException(HtmlTextArea.TAG_NAME, NAME_ATTRIBUTE, name);
765         }
766         return list.get(0);
767     }
768 
769     /**
770      * Returns all the {@link HtmlRadioButtonInput} elements in this form that have the specified name.
771      *
772      * @param name the name to search for
773      * @return all the {@link HtmlRadioButtonInput} elements in this form that have the specified name
774      */
775     public List<HtmlRadioButtonInput> getRadioButtonsByName(final String name) {
776         WebAssert.notNull("name", name);
777 
778         final List<HtmlRadioButtonInput> results = new ArrayList<>();
779 
780         for (final HtmlElement element : getInputsByName(name)) {
781             if (element instanceof HtmlRadioButtonInput input) {
782                 results.add(input);
783             }
784         }
785 
786         return results;
787     }
788 
789     /**
790      * Selects the specified radio button in the form. Only a radio button that is actually contained
791      * in the form can be selected.
792      *
793      * @param radioButtonInput the radio button to select
794      */
795     void setCheckedRadioButton(final HtmlRadioButtonInput radioButtonInput) {
796         if (radioButtonInput.getEnclosingForm() == null) {
797             throw new IllegalArgumentException("HtmlRadioButtonInput is not child of this HtmlForm");
798         }
799         final List<HtmlRadioButtonInput> radios = getRadioButtonsByName(radioButtonInput.getNameAttribute());
800 
801         for (final HtmlRadioButtonInput input : radios) {
802             input.setCheckedInternal(input == radioButtonInput);
803         }
804     }
805 
806     /**
807      * Returns the first checked radio button with the specified name. If none of
808      * the radio buttons by that name are checked, this method returns {@code null}.
809      *
810      * @param name the name of the radio button
811      * @return the first checked radio button with the specified name
812      */
813     public HtmlRadioButtonInput getCheckedRadioButton(final String name) {
814         WebAssert.notNull("name", name);
815 
816         for (final HtmlRadioButtonInput input : getRadioButtonsByName(name)) {
817             if (input.isChecked()) {
818                 return input;
819             }
820         }
821         return null;
822     }
823 
824     /**
825      * Returns the value of the attribute {@code action}. Refer to the <a
826      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
827      * details on the use of this attribute.
828      *
829      * @return the value of the attribute {@code action} or an empty string if that attribute isn't defined
830      */
831     public final String getActionAttribute() {
832         return getAttributeDirect("action");
833     }
834 
835     /**
836      * Sets the value of the attribute {@code action}. Refer to the <a
837      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
838      * details on the use of this attribute.
839      *
840      * @param action the value of the attribute {@code action}
841      */
842     public final void setActionAttribute(final String action) {
843         setAttribute("action", action);
844     }
845 
846     /**
847      * Returns the value of the attribute {@code method}. Refer to the <a
848      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
849      * details on the use of this attribute.
850      *
851      * @return the value of the attribute {@code method} or an empty string if that attribute isn't defined
852      */
853     public final String getMethodAttribute() {
854         return getAttributeDirect("method");
855     }
856 
857     /**
858      * Sets the value of the attribute {@code method}. Refer to the <a
859      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
860      * details on the use of this attribute.
861      *
862      * @param method the value of the attribute {@code method}
863      */
864     public final void setMethodAttribute(final String method) {
865         setAttribute("method", method);
866     }
867 
868     /**
869      * Returns the value of the attribute {@code name}. Refer to the <a
870      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
871      * details on the use of this attribute.
872      *
873      * @return the value of the attribute {@code name} or an empty string if that attribute isn't defined
874      */
875     public final String getNameAttribute() {
876         return getAttributeDirect(NAME_ATTRIBUTE);
877     }
878 
879     /**
880      * Sets the value of the attribute {@code name}. Refer to the <a
881      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
882      * details on the use of this attribute.
883      *
884      * @param name the value of the attribute {@code name}
885      */
886     public final void setNameAttribute(final String name) {
887         setAttribute(NAME_ATTRIBUTE, name);
888     }
889 
890     /**
891      * Returns the value of the attribute {@code enctype}. Refer to the <a
892      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
893      * details on the use of this attribute. "Enctype" is the encoding type
894      * used when submitting a form back to the server.
895      *
896      * @return the value of the attribute {@code enctype} or an empty string if that attribute isn't defined
897      */
898     public final String getEnctypeAttribute() {
899         return getAttributeDirect("enctype");
900     }
901 
902     /**
903      * Sets the value of the attribute {@code enctype}. Refer to the <a
904      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
905      * details on the use of this attribute. "Enctype" is the encoding type
906      * used when submitting a form back to the server.
907      *
908      * @param encoding the value of the attribute {@code enctype}
909      */
910     public final void setEnctypeAttribute(final String encoding) {
911         setAttribute("enctype", encoding);
912     }
913 
914     /**
915      * Returns the value of the attribute {@code onsubmit}. Refer to the <a
916      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
917      * details on the use of this attribute.
918      *
919      * @return the value of the attribute {@code onsubmit} or an empty string if that attribute isn't defined
920      */
921     public final String getOnSubmitAttribute() {
922         return getAttributeDirect("onsubmit");
923     }
924 
925     /**
926      * Returns the value of the attribute {@code onreset}. Refer to the <a
927      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
928      * details on the use of this attribute.
929      *
930      * @return the value of the attribute {@code onreset} or an empty string if that attribute isn't defined
931      */
932     public final String getOnResetAttribute() {
933         return getAttributeDirect("onreset");
934     }
935 
936     /**
937      * Returns the value of the attribute {@code accept}. Refer to the <a
938      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
939      * details on the use of this attribute.
940      *
941      * @return the value of the attribute {@code accept} or an empty string if that attribute isn't defined
942      */
943     public final String getAcceptAttribute() {
944         return getAttribute(HttpHeader.ACCEPT_LC);
945     }
946 
947     /**
948      * Returns the value of the attribute {@code accept-charset}. Refer to the <a
949      * href='http://www.w3.org/TR/html401/interact/forms.html#adef-accept-charset'>
950      * HTML 4.01</a> documentation for details on the use of this attribute.
951      *
952      * @return the value of the attribute {@code accept-charset} or an empty string if that attribute isn't defined
953      */
954     public final String getAcceptCharsetAttribute() {
955         return getAttribute("accept-charset");
956     }
957 
958     /**
959      * Returns the value of the attribute {@code target}. Refer to the <a
960      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
961      * details on the use of this attribute.
962      *
963      * @return the value of the attribute {@code target} or an empty string if that attribute isn't defined
964      */
965     public final String getTargetAttribute() {
966         return getAttributeDirect("target");
967     }
968 
969     /**
970      * Sets the value of the attribute {@code target}. Refer to the <a
971      * href='http://www.w3.org/TR/html401/'>HTML 4.01</a> documentation for
972      * details on the use of this attribute.
973      *
974      * @param target the value of the attribute {@code target}
975      */
976     public final void setTargetAttribute(final String target) {
977         setAttribute("target", target);
978     }
979 
980     /**
981      * Returns the value of the attribute {@code rel}. Refer to the
982      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
983      * documentation for details on the use of this attribute.
984      *
985      * @return the value of the attribute {@code rel} or an empty string if that attribute isn't defined
986      */
987     public final String getRelAttribute() {
988         return getAttributeDirect("rel");
989     }
990 
991     /**
992      * Returns the first input in this form with the specified value.
993      * @param value the value to search for
994      * @param <I> the input type
995      * @return the first input in this form with the specified value
996      * @throws ElementNotFoundException if this form does not contain any inputs with the specified value
997      */
998     @SuppressWarnings("unchecked")
999     public <I extends HtmlInput> I getInputByValue(final String value) throws ElementNotFoundException {
1000         final List<HtmlInput> list = getInputsByValue(value);
1001         if (list.isEmpty()) {
1002             throw new ElementNotFoundException(HtmlInput.TAG_NAME, VALUE_ATTRIBUTE, value);
1003         }
1004         return (I) list.get(0);
1005     }
1006 
1007     /**
1008      * Returns all the inputs in this form with the specified value.
1009      * @param value the value to search for
1010      * @return all the inputs in this form with the specified value
1011      */
1012     public List<HtmlInput> getInputsByValue(final String value) {
1013         final List<HtmlInput> results = new ArrayList<>();
1014 
1015         for (final HtmlElement element : getElements(htmlElement -> htmlElement instanceof HtmlInput)) {
1016             if (Objects.equals(((HtmlInput) element).getValue(), value)) {
1017                 results.add((HtmlInput) element);
1018             }
1019         }
1020 
1021         return results;
1022     }
1023 
1024     /**
1025      * {@inheritDoc}
1026      */
1027     @Override
1028     protected void preventDefault() {
1029         isPreventDefault_ = true;
1030     }
1031 
1032     /**
1033      * Returns whether form validation is disabled.
1034      *
1035      * @return {@code true} if the {@code novalidate} attribute is present
1036      */
1037     public final boolean isNoValidate() {
1038         return hasAttribute(ATTRIBUTE_NOVALIDATE);
1039     }
1040 
1041     /**
1042      * Sets the value of the attribute {@code novalidate}.
1043      *
1044      * @param noValidate the value of the attribute {@code novalidate}
1045      */
1046     public final void setNoValidate(final boolean noValidate) {
1047         if (noValidate) {
1048             setAttribute(ATTRIBUTE_NOVALIDATE, ATTRIBUTE_NOVALIDATE);
1049         }
1050         else {
1051             removeAttribute(ATTRIBUTE_NOVALIDATE);
1052         }
1053     }
1054 
1055     /**
1056      * Register an element to the past names map with the specified name.
1057      * @param name name or id attribute of the element
1058      * @param element the element to register
1059      */
1060     public void registerPastName(final String name, final HtmlElement element) {
1061         if (pastNamesMap_ == null) {
1062             pastNamesMap_ = new HashMap<>();
1063         }
1064         pastNamesMap_.put(name, element);
1065     }
1066 
1067     /**
1068      * Return the element registered in the past names map with the specified name.
1069      * If the element is no longer owned by this form, the entry is removed and null is returned.
1070      * @param name name or id attribute of the element
1071      * @return the element, or null if not found or no longer owned by this form
1072      */
1073     public HtmlElement getNamedElement(final String name) {
1074         if (pastNamesMap_ == null) {
1075             return null;
1076         }
1077         final HtmlElement element = pastNamesMap_.get(name);
1078         if (element != null && element.getEnclosingForm() != this) {
1079             pastNamesMap_.remove(name);
1080             return null;
1081         }
1082         return element;
1083     }
1084 }