forked from HtmlUnit/htmlunit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlPage.java
More file actions
2999 lines (2705 loc) · 112 KB
/
HtmlPage.java
File metadata and controls
2999 lines (2705 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2026 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.htmlunit.html;
import static org.htmlunit.BrowserVersionFeatures.EVENT_FOCUS_ON_LOAD;
import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlunit.Cache;
import org.htmlunit.ElementNotFoundException;
import org.htmlunit.FailingHttpStatusCodeException;
import org.htmlunit.History;
import org.htmlunit.HttpHeader;
import org.htmlunit.OnbeforeunloadHandler;
import org.htmlunit.Page;
import org.htmlunit.ScriptResult;
import org.htmlunit.SgmlPage;
import org.htmlunit.TopLevelWindow;
import org.htmlunit.WebAssert;
import org.htmlunit.WebClient;
import org.htmlunit.WebClientOptions;
import org.htmlunit.WebRequest;
import org.htmlunit.WebResponse;
import org.htmlunit.WebWindow;
import org.htmlunit.corejs.javascript.Function;
import org.htmlunit.corejs.javascript.Script;
import org.htmlunit.corejs.javascript.Scriptable;
import org.htmlunit.corejs.javascript.ScriptableObject;
import org.htmlunit.corejs.javascript.VarScope;
import org.htmlunit.css.ComputedCssStyleDeclaration;
import org.htmlunit.css.CssStyleSheet;
import org.htmlunit.html.impl.SimpleRange;
import org.htmlunit.html.parser.HTMLParserDOMBuilder;
import org.htmlunit.http.HttpStatus;
import org.htmlunit.javascript.AbstractJavaScriptEngine;
import org.htmlunit.javascript.HtmlUnitScriptable;
import org.htmlunit.javascript.JavaScriptEngine;
import org.htmlunit.javascript.PostponedAction;
import org.htmlunit.javascript.host.Window;
import org.htmlunit.javascript.host.event.BeforeUnloadEvent;
import org.htmlunit.javascript.host.event.Event;
import org.htmlunit.javascript.host.event.EventTarget;
import org.htmlunit.javascript.host.html.HTMLDocument;
import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
import org.htmlunit.util.MimeType;
import org.htmlunit.util.SerializableLock;
import org.htmlunit.util.UrlUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.ProcessingInstruction;
/**
* A representation of an HTML page returned from a server.
* <p>
* This class provides different methods to access the page's content like
* {@link #getForms()}, {@link #getAnchors()}, {@link #getElementById(String)}, ... as well as the
* very powerful inherited methods {@link #getByXPath(String)} and {@link #getFirstByXPath(String)}
* for fine grained user specific access to child nodes.
* </p>
* <p>
* Child elements allowing user interaction provide methods for this purpose like {@link HtmlAnchor#click()},
* {@link HtmlInput#type(String)}, {@link HtmlOption#setSelected(boolean)}, ...
* </p>
* <p>
* HtmlPage instances should not be instantiated directly. They will be returned by {@link WebClient#getPage(String)}
* when the content type of the server's response is <code>text/html</code> (or one of its variations).<br>
* <br>
* <b>Example:</b><br>
* <br>
* <code>
* final HtmlPage page = webClient.{@link WebClient#getPage(String) getPage}("http://mywebsite/some/page.html");
* </code>
* </p>
*
* @author Mike Bowler
* @author Alex Nikiforoff
* @author Noboru Sinohara
* @author David K. Taylor
* @author Andreas Hangler
* @author Christian Sell
* @author Chris Erskine
* @author Marc Guillemot
* @author Ahmed Ashour
* @author Daniel Gredler
* @author Dmitri Zoubkov
* @author Sudhan Moghe
* @author Ethan Glasser-Camp
* @author Tom Anderson
* @author Ronald Brill
* @author Frank Danek
* @author Joerg Werner
* @author Atsushi Nakagawa
* @author Rural Hunter
* @author Ronny Shapiro
* @author Lai Quang Duong
* @author Sven Strickroth
*/
@SuppressWarnings("PMD.TooManyFields")
public class HtmlPage extends SgmlPage {
private static final Log LOG = LogFactory.getLog(HtmlPage.class);
private static final Comparator<DomElement> DOCUMENT_POSITION_COMPERATOR = new DocumentPositionComparator();
private HTMLParserDOMBuilder domBuilder_;
private transient Charset originalCharset_;
private final Object lock_ = new SerializableLock(); // used for synchronization
private Map<String, MappedElementIndexEntry> idMap_ = new ConcurrentHashMap<>();
private Map<String, MappedElementIndexEntry> nameMap_ = new ConcurrentHashMap<>();
// The id/name lookup index is built lazily on first use. Until then,
// notifyNodeAdded / fireAttributeChange skip the per-element index updates.
// Reads must call ensureMappedElementsBuilt() before consulting idMap_/nameMap_.
private boolean mappedElementsBuilt_;
private List<BaseFrameElement> frameElements_ = new ArrayList<>();
private int parserCount_;
private int snippetParserCount_;
private int inlineSnippetParserCount_;
private Collection<HtmlAttributeChangeListener> attributeListeners_;
private List<PostponedAction> afterLoadActions_ = Collections.synchronizedList(new ArrayList<>());
private boolean cleaning_;
private HtmlBase base_;
private URL baseUrl_;
private List<AutoCloseable> autoCloseableList_;
private ElementFromPointHandler elementFromPointHandler_;
private DomElement elementWithFocus_;
private List<SimpleRange> selectionRanges_ = new ArrayList<>(3);
private transient ComputedStylesCache computedStylesCache_;
private static final HashSet<String> TABBABLE_TAGS =
new HashSet<>(Arrays.asList(HtmlAnchor.TAG_NAME, HtmlArea.TAG_NAME,
HtmlButton.TAG_NAME, HtmlInput.TAG_NAME, HtmlObject.TAG_NAME,
HtmlSelect.TAG_NAME, HtmlTextArea.TAG_NAME));
private static final HashSet<String> ACCEPTABLE_TAG_NAMES =
new HashSet<>(Arrays.asList(HtmlAnchor.TAG_NAME, HtmlArea.TAG_NAME,
HtmlButton.TAG_NAME, HtmlInput.TAG_NAME, HtmlLabel.TAG_NAME,
HtmlLegend.TAG_NAME, HtmlTextArea.TAG_NAME));
/** Definition of special cases for the smart DomHtmlAttributeChangeListenerImpl */
private static final Set<String> ATTRIBUTES_AFFECTING_PARENT = new HashSet<>(Arrays.asList(
"style",
"class",
"height",
"width"));
static class DocumentPositionComparator implements Comparator<DomElement>, Serializable {
@Override
public int compare(final DomElement elt1, final DomElement elt2) {
final short relation = elt1.compareDocumentPosition(elt2);
if (relation == 0) {
return 0; // same node
}
if ((relation & DOCUMENT_POSITION_CONTAINS) != 0 || (relation & DOCUMENT_POSITION_PRECEDING) != 0) {
return 1;
}
return -1;
}
}
/**
* Creates an instance of HtmlPage.
* An HtmlPage instance is normally retrieved with {@link WebClient#getPage(String)}.
*
* @param webResponse the web response that was used to create this page
* @param webWindow the window that this page is being loaded into
*/
public HtmlPage(final WebResponse webResponse, final WebWindow webWindow) {
super(webResponse, webWindow);
}
/**
* {@inheritDoc}
*/
@Override
public HtmlPage getPage() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasCaseSensitiveTagNames() {
return false;
}
/**
* Initialize this page.
* @throws IOException if an IO problem occurs
* @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
* {@link org.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set
* to true.
*/
@Override
public void initialize() throws IOException, FailingHttpStatusCodeException {
final WebWindow enclosingWindow = getEnclosingWindow();
final boolean isAboutBlank = getUrl() == UrlUtils.URL_ABOUT_BLANK;
if (isAboutBlank) {
// a frame contains first a faked "about:blank" before its real content specified by src gets loaded
if (enclosingWindow instanceof FrameWindow window
&& !window.getFrameElement().isContentLoaded()) {
return;
}
// save the URL that should be used to resolve relative URLs in this page
if (enclosingWindow instanceof TopLevelWindow topWindow) {
final WebWindow openerWindow = topWindow.getOpener();
if (openerWindow != null && openerWindow.getEnclosedPage() != null) {
baseUrl_ = openerWindow.getEnclosedPage().getWebResponse().getWebRequest().getUrl();
}
}
}
if (!isAboutBlank) {
setReadyState(READY_STATE_INTERACTIVE);
getDocumentElement().setReadyState(READY_STATE_INTERACTIVE);
executeEventHandlersIfNeeded(Event.TYPE_READY_STATE_CHANGE);
}
executeDeferredScriptsIfNeeded();
executeEventHandlersIfNeeded(Event.TYPE_DOM_DOCUMENT_LOADED);
// postponed actions are more or less the async scripts,
// they are running in real browsers whenever the download is done
processPostponedActionsIfNeeded();
loadFrames();
// don't set the ready state if we really load the blank page into the window
// see Node.initInlineFrameIfNeeded()
if (!isAboutBlank) {
setReadyState(READY_STATE_COMPLETE);
getDocumentElement().setReadyState(READY_STATE_COMPLETE);
executeEventHandlersIfNeeded(Event.TYPE_READY_STATE_CHANGE);
}
// frame initialization has a different order
boolean isFrameWindow = enclosingWindow instanceof FrameWindow;
boolean isFirstPageInFrameWindow = false;
if (isFrameWindow) {
isFrameWindow = ((FrameWindow) enclosingWindow).getFrameElement() instanceof HtmlFrame;
final History hist = enclosingWindow.getHistory();
if (hist.getLength() > 0 && UrlUtils.URL_ABOUT_BLANK == hist.getUrl(0)) {
isFirstPageInFrameWindow = hist.getLength() <= 2;
}
else {
isFirstPageInFrameWindow = enclosingWindow.getHistory().getLength() < 2;
}
}
if (isFrameWindow && !isFirstPageInFrameWindow) {
executeEventHandlersIfNeeded(Event.TYPE_LOAD);
}
for (final BaseFrameElement frameElement : new ArrayList<>(frameElements_)) {
if (frameElement instanceof HtmlFrame) {
final Page page = frameElement.getEnclosedWindow().getEnclosedPage();
if (page != null && page.isHtmlPage()) {
((HtmlPage) page).executeEventHandlersIfNeeded(Event.TYPE_LOAD);
}
}
}
if (!isFrameWindow) {
executeEventHandlersIfNeeded(Event.TYPE_LOAD);
if (!isAboutBlank && enclosingWindow.getWebClient().isJavaScriptEnabled()
&& hasFeature(EVENT_FOCUS_ON_LOAD)) {
final HtmlElement body = getBody();
if (body != null) {
final Event event = new Event((Window) enclosingWindow.getScriptableObject(), Event.TYPE_FOCUS);
body.fireEvent(event);
}
}
}
try {
while (!afterLoadActions_.isEmpty()) {
final PostponedAction action = afterLoadActions_.remove(0);
action.execute();
}
}
catch (final IOException e) {
throw e;
}
catch (final Exception e) {
throw new RuntimeException(e);
}
executeRefreshIfNeeded();
}
/**
* Adds an action that should be executed once the page has been loaded.
* @param action the action
*/
void addAfterLoadAction(final PostponedAction action) {
afterLoadActions_.add(action);
}
/**
* Clean up this page.
*/
@Override
public void cleanUp() {
//To avoid endless recursion caused by window.close() in onUnload
if (cleaning_) {
return;
}
cleaning_ = true;
try {
super.cleanUp();
executeEventHandlersIfNeeded(Event.TYPE_UNLOAD);
deregisterFramesIfNeeded();
}
finally {
cleaning_ = false;
if (autoCloseableList_ != null) {
for (final AutoCloseable closeable : new ArrayList<>(autoCloseableList_)) {
try {
closeable.close();
}
catch (final Exception e) {
LOG.error("Closing the autoclosable " + closeable + " failed", e);
}
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public HtmlElement getDocumentElement() {
return (HtmlElement) super.getDocumentElement();
}
/**
* @return the <code>body</code> element, or {@code null} if it does not yet exist
*/
public HtmlBody getBody() {
final DomElement doc = getDocumentElement();
if (doc != null) {
for (final DomNode node : doc.getChildren()) {
if (node instanceof HtmlBody body) {
return body;
}
}
}
return null;
}
/**
* Returns the head element.
* @return the head element
*/
public HtmlElement getHead() {
final DomElement doc = getDocumentElement();
if (doc != null) {
for (final DomNode node : doc.getChildren()) {
if (node instanceof HtmlHead) {
return (HtmlElement) node;
}
}
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Document getOwnerDocument() {
return null;
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public org.w3c.dom.Node importNode(final org.w3c.dom.Node importedNode, final boolean deep) {
throw new UnsupportedOperationException("HtmlPage.importNode is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public String getInputEncoding() {
throw new UnsupportedOperationException("HtmlPage.getInputEncoding is not yet implemented.");
}
/**
* {@inheritDoc}
*/
@Override
public String getXmlEncoding() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean getXmlStandalone() {
return false;
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public void setXmlStandalone(final boolean xmlStandalone) throws DOMException {
throw new UnsupportedOperationException("HtmlPage.setXmlStandalone is not yet implemented.");
}
/**
* {@inheritDoc}
*/
@Override
public String getXmlVersion() {
return null;
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public void setXmlVersion(final String xmlVersion) throws DOMException {
throw new UnsupportedOperationException("HtmlPage.setXmlVersion is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public boolean getStrictErrorChecking() {
throw new UnsupportedOperationException("HtmlPage.getStrictErrorChecking is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public void setStrictErrorChecking(final boolean strictErrorChecking) {
throw new UnsupportedOperationException("HtmlPage.setStrictErrorChecking is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public String getDocumentURI() {
throw new UnsupportedOperationException("HtmlPage.getDocumentURI is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public void setDocumentURI(final String documentURI) {
throw new UnsupportedOperationException("HtmlPage.setDocumentURI is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public org.w3c.dom.Node adoptNode(final org.w3c.dom.Node source) throws DOMException {
throw new UnsupportedOperationException("HtmlPage.adoptNode is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public DOMConfiguration getDomConfig() {
throw new UnsupportedOperationException("HtmlPage.getDomConfig is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public org.w3c.dom.Node renameNode(final org.w3c.dom.Node newNode, final String namespaceURI,
final String qualifiedName) throws DOMException {
throw new UnsupportedOperationException("HtmlPage.renameNode is not yet implemented.");
}
/**
* {@inheritDoc}
*/
@Override
public Charset getCharset() {
if (originalCharset_ == null) {
originalCharset_ = getWebResponse().getContentCharset();
}
return originalCharset_;
}
/**
* {@inheritDoc}
*/
@Override
public String getContentType() {
return getWebResponse().getContentType();
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public DOMImplementation getImplementation() {
throw new UnsupportedOperationException("HtmlPage.getImplementation is not yet implemented.");
}
/**
* {@inheritDoc}
* @param tagName the tag name, preferably in lowercase
*/
@Override
public DomElement createElement(String tagName) {
if (tagName.indexOf(':') == -1) {
tagName = org.htmlunit.util.StringUtils.toRootLowerCase(tagName);
}
return getWebClient().getPageCreator().getHtmlParser().getFactory(tagName)
.createElementNS(this, null, tagName, null);
}
/**
* {@inheritDoc}
*/
@Override
public DomElement createElementNS(final String namespaceURI, final String qualifiedName) {
return getWebClient().getPageCreator().getHtmlParser()
.getElementFactory(this, namespaceURI, qualifiedName, false, true)
.createElementNS(this, namespaceURI, qualifiedName, null);
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public Attr createAttributeNS(final String namespaceURI, final String qualifiedName) {
throw new UnsupportedOperationException("HtmlPage.createAttributeNS is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public EntityReference createEntityReference(final String id) {
throw new UnsupportedOperationException("HtmlPage.createEntityReference is not yet implemented.");
}
/**
* {@inheritDoc}
* Not yet implemented.
*/
@Override
public ProcessingInstruction createProcessingInstruction(final String namespaceURI, final String qualifiedName) {
throw new UnsupportedOperationException("HtmlPage.createProcessingInstruction is not yet implemented.");
}
/**
* {@inheritDoc}
*/
@Override
public DomElement getElementById(final String elementId) {
if (elementId != null) {
ensureMappedElementsBuilt();
final MappedElementIndexEntry elements = idMap_.get(elementId);
if (elements != null) {
return elements.first();
}
}
return null;
}
/**
* Returns the {@link HtmlAnchor} with the specified name.
*
* @param name the name to search by
* @return the {@link HtmlAnchor} with the specified name
* @throws ElementNotFoundException if the anchor could not be found
*/
public HtmlAnchor getAnchorByName(final String name) throws ElementNotFoundException {
return getDocumentElement().getOneHtmlElementByAttribute("a", DomElement.NAME_ATTRIBUTE, name);
}
/**
* Returns the {@link HtmlAnchor} with the specified href.
*
* @param href the string to search by
* @return the HtmlAnchor
* @throws ElementNotFoundException if the anchor could not be found
*/
public HtmlAnchor getAnchorByHref(final String href) throws ElementNotFoundException {
return getDocumentElement().getOneHtmlElementByAttribute("a", "href", href);
}
/**
* Returns a list of all anchors contained in this page.
* @return the list of {@link HtmlAnchor} in this page
*/
public List<HtmlAnchor> getAnchors() {
return getDocumentElement().getElementsByTagNameImpl("a");
}
/**
* Returns the first anchor with the specified text.
* @param text the text to search for
* @return the first anchor that was found
* @throws ElementNotFoundException if no anchors are found with the specified text
*/
public HtmlAnchor getAnchorByText(final String text) throws ElementNotFoundException {
WebAssert.notNull("text", text);
for (final HtmlAnchor anchor : getAnchors()) {
if (text.equals(anchor.asNormalizedText())) {
return anchor;
}
}
throw new ElementNotFoundException("a", "<text>", text);
}
/**
* Returns the first form that matches the specified name.
* @param name the name to search for
* @return the first form
* @exception ElementNotFoundException If no forms match the specified result.
*/
public HtmlForm getFormByName(final String name) throws ElementNotFoundException {
final List<HtmlForm> forms = getDocumentElement()
.getElementsByAttribute("form", DomElement.NAME_ATTRIBUTE, name);
if (forms.isEmpty()) {
throw new ElementNotFoundException("form", DomElement.NAME_ATTRIBUTE, name);
}
return forms.get(0);
}
/**
* Returns a list of all the forms in this page.
* @return all the forms in this page
*/
public List<HtmlForm> getForms() {
return getDocumentElement().getElementsByTagNameImpl("form");
}
/**
* Given a relative URL (ie <code>/foo</code>), returns a fully-qualified URL based on
* the URL that was used to load this page.
*
* @param relativeUrl the relative URL
* @return the fully-qualified URL for the specified relative URL
* @exception MalformedURLException if an error occurred when creating a URL object
*/
public URL getFullyQualifiedUrl(String relativeUrl) throws MalformedURLException {
// to handle http: and http:/ in FF (Bug #474)
boolean incorrectnessNotified = false;
while (relativeUrl.startsWith("http:") && !relativeUrl.startsWith("http://")) {
if (!incorrectnessNotified) {
notifyIncorrectness("Incorrect URL \"" + relativeUrl + "\" has been corrected");
incorrectnessNotified = true;
}
relativeUrl = "http:/" + relativeUrl.substring(5);
}
return WebClient.expandUrl(getBaseURL(), relativeUrl);
}
/**
* Given a target attribute value, resolve the target using a base target for the page.
*
* @param elementTarget the target specified as an attribute of the element
* @return the resolved target to use for the element
*/
public String getResolvedTarget(final String elementTarget) {
final String resolvedTarget;
if (base_ == null) {
resolvedTarget = elementTarget;
}
else if (elementTarget != null && !elementTarget.isEmpty()) {
resolvedTarget = elementTarget;
}
else {
resolvedTarget = base_.getTargetAttribute();
}
return resolvedTarget;
}
/**
* Returns a list of ids (strings) that correspond to the tabbable elements
* in this page. Return them in the same order specified in {@link #getTabbableElements}
*
* @return the list of id's
*/
public List<String> getTabbableElementIds() {
final List<String> list = new ArrayList<>();
for (final HtmlElement element : getTabbableElements()) {
list.add(element.getId());
}
return Collections.unmodifiableList(list);
}
/**
* Returns a list of all elements that are tabbable in the order that will
* be used for tabbing.<p>
*
* The rules for determining tab order are as follows:
* <ol>
* <li>Those elements that support the tabindex attribute and assign a
* positive value to it are navigated first. Navigation proceeds from the
* element with the lowest tabindex value to the element with the highest
* value. Values need not be sequential nor must they begin with any
* particular value. Elements that have identical tabindex values should
* be navigated in the order they appear in the character stream.
* <li>Those elements that do not support the tabindex attribute or
* support it and assign it a value of "0" are navigated next. These
* elements are navigated in the order they appear in the character
* stream.
* <li>Elements that are disabled do not participate in the tabbing
* order.
* </ol>
* Additionally, the value of tabindex must be within 0 and 32767. Any
* values outside this range will be ignored.<p>
*
* The following elements support the <code>tabindex</code> attribute:
* A, AREA, BUTTON, INPUT, OBJECT, SELECT, and TEXTAREA.
*
* @return all the tabbable elements in proper tab order
*/
public List<HtmlElement> getTabbableElements() {
final List<HtmlElement> tabbableElements = new ArrayList<>();
for (final HtmlElement element : getHtmlElementDescendants()) {
final String tagName = element.getTagName();
if (TABBABLE_TAGS.contains(tagName)) {
final boolean disabled = element.isDisabledElementAndDisabled();
if (!disabled && !HtmlElement.TAB_INDEX_OUT_OF_BOUNDS.equals(element.getTabIndex())) {
tabbableElements.add(element);
}
}
}
tabbableElements.sort(createTabOrderComparator());
return Collections.unmodifiableList(tabbableElements);
}
private static Comparator<HtmlElement> createTabOrderComparator() {
return (element1, element2) -> {
final Short i1 = element1.getTabIndex();
final Short i2 = element2.getTabIndex();
final short index1;
if (i1 == null) {
index1 = -1;
}
else {
index1 = i1.shortValue();
}
final short index2;
if (i2 == null) {
index2 = -1;
}
else {
index2 = i2.shortValue();
}
final int result;
if (index1 > 0 && index2 > 0) {
result = index1 - index2;
}
else if (index1 > 0) {
result = -1;
}
else if (index2 > 0) {
result = 1;
}
else if (index1 == index2) {
result = 0;
}
else {
result = index2 - index1;
}
return result;
};
}
/**
* Returns the HTML element that is assigned to the specified access key. An
* access key (aka mnemonic key) is used for keyboard navigation of the
* page.<p>
*
* Only the following HTML elements may have <code>accesskey</code>s defined: A, AREA,
* BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA.
*
* @param accessKey the key to look for
* @return the HTML element that is assigned to the specified key or null
* if no elements can be found that match the specified key.
*/
public HtmlElement getHtmlElementByAccessKey(final char accessKey) {
final List<HtmlElement> elements = getHtmlElementsByAccessKey(accessKey);
if (elements.isEmpty()) {
return null;
}
return elements.get(0);
}
/**
* Returns all the HTML elements that are assigned to the specified access key. An
* access key (aka mnemonic key) is used for keyboard navigation of the
* page.<p>
*
* The HTML specification seems to indicate that one accesskey cannot be used
* for multiple elements however Internet Explorer does seem to support this.
* It's worth noting that Firefox does not support multiple elements with one
* access key so you are making your HTML browser specific if you rely on this
* feature.<p>
*
* Only the following HTML elements may have <code>accesskey</code>s defined: A, AREA,
* BUTTON, INPUT, LABEL, LEGEND, and TEXTAREA.
*
* @param accessKey the key to look for
* @return the elements that are assigned to the specified accesskey
*/
public List<HtmlElement> getHtmlElementsByAccessKey(final char accessKey) {
final List<HtmlElement> elements = new ArrayList<>();
final String searchString = Character.toString(accessKey).toLowerCase(Locale.ROOT);
for (final HtmlElement element : getHtmlElementDescendants()) {
if (ACCEPTABLE_TAG_NAMES.contains(element.getTagName())) {
final String accessKeyAttribute = element.getAttributeDirect("accesskey");
if (searchString.equalsIgnoreCase(accessKeyAttribute)) {
elements.add(element);
}
}
}
return elements;
}
/**
* <p>Executes the specified JavaScript code within the page. The usage would be similar to what can
* be achieved to execute JavaScript in the current page by entering "javascript:...some JS code..."
* in the URL field of a native browser.</p>
* <p><b>Note:</b> the provided code won't be executed if JavaScript has been disabled on the WebClient
* (see {@link org.htmlunit.WebClient#isJavaScriptEnabled()}).</p>
* @param sourceCode the JavaScript code to execute
* @return a ScriptResult which will contain both the current page (which may be different from
* the previous page) and a JavaScript result object
*/
public ScriptResult executeJavaScript(final String sourceCode) {
return executeJavaScript(sourceCode, "injected script", 1);
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
* <p>
* Execute the specified JavaScript if a JavaScript engine was successfully
* instantiated. If this JavaScript causes the current page to be reloaded
* (through location="" or form.submit()) then return the new page, otherwise
* return the current page.
* </p>
* <p><b>Please note:</b> Although this method is public, it is not intended for
* general execution of JavaScript. Users of HtmlUnit should interact with the pages
* as a user would by clicking on buttons or links and having the JavaScript event
* handlers execute as needed.
* </p>
*
* @param sourceCode the JavaScript code to execute
* @param sourceName the name for this chunk of code (will be displayed in error messages)
* @param startLine the line at which the script source starts
* @return a ScriptResult which will contain both the current page (which may be different from
* the previous page) and a JavaScript result object.
*/
public ScriptResult executeJavaScript(String sourceCode, final String sourceName, final int startLine) {
if (!getWebClient().isJavaScriptEnabled()) {
return new ScriptResult(JavaScriptEngine.UNDEFINED);
}
if (org.htmlunit.util.StringUtils.startsWithIgnoreCase(sourceCode,
JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
sourceCode = sourceCode.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length()).trim();
if (sourceCode.startsWith("return ")) {
sourceCode = sourceCode.substring("return ".length());
}
}
final Window window = getEnclosingWindow().getScriptableObject();
final VarScope scope = ScriptableObject.getTopLevelScope(window.getParentScope());
final Object result = getWebClient().getJavaScriptEngine()
.execute(this, scope, sourceCode, sourceName, startLine);
return new ScriptResult(result);
}
/** Various possible external JavaScript file loading results. */
enum JavaScriptLoadResult {
/** The load was aborted and nothing was done. */
NOOP,
/** The load was aborted and nothing was done. */
NO_CONTENT,
/** The external JavaScript file was downloaded and compiled successfully. */
SUCCESS,
/** The external JavaScript file was not downloaded successfully. */
DOWNLOAD_ERROR,
/** The external JavaScript file was downloaded but was not compiled successfully. */
COMPILATION_ERROR
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
*
* @param srcAttribute the source attribute from the script tag
* @param scriptCharset the charset from the script tag
* @return the result of loading the specified external JavaScript file
* @throws FailingHttpStatusCodeException if the request's status code indicates a request
* failure and the {@link WebClient} was configured to throw exceptions on failing
* HTTP status codes
*/
JavaScriptLoadResult loadExternalJavaScriptFile(final String srcAttribute, final Charset scriptCharset)
throws FailingHttpStatusCodeException {
final WebClient client = getWebClient();
if (org.htmlunit.util.StringUtils.isBlank(srcAttribute) || !client.isJavaScriptEnabled()) {
return JavaScriptLoadResult.NOOP;
}
final URL scriptURL;
try {