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