View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_URL_FILE_WITHOUT_HOST;
18  
19  import java.net.MalformedURLException;
20  import java.util.List;
21  import java.util.UUID;
22  
23  import org.apache.commons.lang3.StringUtils;
24  import org.htmlunit.BrowserVersion;
25  import org.htmlunit.Page;
26  import org.htmlunit.WebWindow;
27  import org.htmlunit.corejs.javascript.Scriptable;
28  import org.htmlunit.javascript.HtmlUnitScriptable;
29  import org.htmlunit.javascript.JavaScriptEngine;
30  import org.htmlunit.javascript.configuration.JsxClass;
31  import org.htmlunit.javascript.configuration.JsxConstructor;
32  import org.htmlunit.javascript.configuration.JsxConstructorAlias;
33  import org.htmlunit.javascript.configuration.JsxFunction;
34  import org.htmlunit.javascript.configuration.JsxGetter;
35  import org.htmlunit.javascript.configuration.JsxSetter;
36  import org.htmlunit.javascript.configuration.JsxStaticFunction;
37  import org.htmlunit.javascript.host.file.Blob;
38  import org.htmlunit.javascript.host.file.File;
39  import org.htmlunit.util.NameValuePair;
40  import org.htmlunit.util.UrlUtils;
41  
42  /**
43   * JavaScript host object for {@code URL}.
44   *
45   * @author Ahmed Ashour
46   * @author Ronald Brill
47   * @author cd alexndr
48   * @author Lai Quang Duong
49   *
50   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">MDN Documentation</a>
51   */
52  @JsxClass
53  public class URL extends HtmlUnitScriptable {
54  
55      private java.net.URL url_;
56  
57      /**
58       * Creates an instance of this object.
59       *
60       * @param url a string representing an absolute or relative URL.
61       *        If {@code url} is a relative URL, {@code base} is required and will be used
62       *        as the base URL. If {@code url} is an absolute URL, a given {@code base} will be ignored.
63       * @param base a string representing the base URL to use when {@code url}
64       *        is a relative URL. If not specified, it defaults to {@code ''}.
65       */
66      @JsxConstructor
67      @JsxConstructorAlias(alias = "webkitURL")
68      public void jsConstructor(final String url, final Object base) {
69          String baseStr = null;
70          if (!JavaScriptEngine.isUndefined(base)) {
71              baseStr = JavaScriptEngine.toString(base);
72          }
73  
74          try {
75              if (org.htmlunit.util.StringUtils.isBlank(baseStr)) {
76                  url_ = UrlUtils.toUrlUnsafe(url);
77              }
78              else {
79                  final java.net.URL baseUrl = UrlUtils.toUrlUnsafe(baseStr);
80                  url_ = UrlUtils.toUrlUnsafe(UrlUtils.resolveUrl(baseUrl, url));
81              }
82              url_ = UrlUtils.removeRedundantPort(url_);
83              if ("file".equals(url_.getProtocol()) && fileWithoutHost()) {
84                  url_ = UrlUtils.removeLocalhostFromFileUrl(url_);
85              }
86          }
87          catch (final MalformedURLException e) {
88              throw JavaScriptEngine.typeError(e.toString());
89          }
90      }
91  
92      /**
93       * The URL.createObjectURL() static method creates a {@code DOMString} containing a URL
94       * representing the object given as parameter.
95       * The new object URL represents the specified {@link File} object or {@link Blob} object
96       * and is registered in the {@link org.htmlunit.BlobUrlStore user-agent-wide blob URL store},
97       * so it can be resolved from any document of the same client.
98       *
99       * @param fileOrBlob the {@link File} or {@link Blob} to create an object URL for
100      * @return the object URL, or {@code null} if the argument is not a supported type
101      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL_static">MDN Documentation</a>
102      */
103     @JsxStaticFunction
104     public static String createObjectURL(final Object fileOrBlob) {
105         if (!(fileOrBlob instanceof Blob blob)) {
106             throw JavaScriptEngine.typeError("URL.createObjectURL: argument 1 is not a Blob.");
107         }
108 
109         final WebWindow webWindow = getWindow(blob).getWebWindow();
110         final Page page = webWindow.getEnclosedPage();
111         final java.net.URL pageUrl = page.getUrl();
112 
113         String origin = "null";
114         if (pageUrl != UrlUtils.URL_ABOUT_BLANK) {
115             final int port = pageUrl.getPort();
116             if (port < 0 || port == pageUrl.getDefaultPort()) {
117                 origin = pageUrl.getProtocol() + "://" + pageUrl.getHost();
118             }
119             else {
120                 origin = pageUrl.getProtocol() + "://" + pageUrl.getHost() + ':' + port;
121             }
122         }
123 
124         final String blobUrl = "blob:" + origin + "/" + UUID.randomUUID();
125         webWindow.getWebClient().getBlobUrlStore().put(blobUrl, blob, page);
126         return blobUrl;
127     }
128 
129     /**
130      * Revokes a {@code blob:} URL, removing its entry from the blob URL store.
131      *
132      * @param objectURL the object URL previously returned by {@link #createObjectURL(Object)}
133      *
134      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL_static">MDN Documentation</a>
135      */
136     @JsxStaticFunction
137     public static void revokeObjectURL(final Scriptable objectURL) {
138         final String url = JavaScriptEngine.toString(objectURL);
139         if (!url.startsWith("blob:")) {
140             return;
141         }
142         getWindow(objectURL).getWebWindow().getWebClient().getBlobUrlStore().remove(url);
143     }
144 
145     /**
146      * Returns the hash portion of the URL, containing a {@code #} followed by the fragment identifier.
147      *
148      * @return the hash portion of the URL, or an empty string if there is no fragment
149      */
150     @JsxGetter
151     public String getHash() {
152         if (url_ == null) {
153             return null;
154         }
155         final String ref = url_.getRef();
156         return ref == null ? "" : "#" + ref;
157     }
158 
159     /**
160      * Sets the {@code hash} property.
161      *
162      * @param fragment the new hash value
163      * @throws MalformedURLException if the resulting URL is malformed
164      */
165     @JsxSetter
166     public void setHash(final String fragment) throws MalformedURLException {
167         if (url_ == null) {
168             return;
169         }
170         url_ = UrlUtils.getUrlWithNewRef(url_, org.htmlunit.util.StringUtils.isEmptyOrNull(fragment) ? null : fragment);
171     }
172 
173     /**
174      * Returns the host portion of the URL, consisting of the hostname and, if the port is non-empty,
175      * a {@code :} followed by the port.
176      *
177      * @return the host
178      */
179     @JsxGetter
180     public String getHost() {
181         if (url_ == null) {
182             return null;
183         }
184         final int port = url_.getPort();
185         return url_.getHost() + (port > 0 ? ":" + port : "");
186     }
187 
188     /**
189      * Sets the {@code host} property.
190      *
191      * @param host the new host value
192      * @throws MalformedURLException if the resulting URL is malformed
193      */
194     @JsxSetter
195     public void setHost(final String host) throws MalformedURLException {
196         if (url_ == null) {
197             return;
198         }
199 
200         String newHost = StringUtils.substringBefore(host, ':');
201         if (org.htmlunit.util.StringUtils.isEmptyOrNull(newHost)) {
202             return;
203         }
204 
205         try {
206             int ip = Integer.parseInt(newHost);
207             final StringBuilder ipString = new StringBuilder();
208             ipString.insert(0, ip % 256);
209             ipString.insert(0, '.');
210 
211             ip = ip / 256;
212             ipString.insert(0, ip % 256);
213             ipString.insert(0, '.');
214 
215             ip = ip / 256;
216             ipString.insert(0, ip % 256);
217             ipString.insert(0, '.');
218             ip = ip / 256;
219             ipString.insert(0, ip % 256);
220 
221             newHost = ipString.toString();
222         }
223         catch (final Exception expected) {
224             // back to string
225         }
226 
227         url_ = UrlUtils.getUrlWithNewHost(url_, newHost);
228 
229         final String newPort = StringUtils.substringAfter(host, ':');
230         if (org.htmlunit.util.StringUtils.isNotBlank(newHost)) {
231             try {
232                 url_ = UrlUtils.getUrlWithNewHostAndPort(url_, newHost, Integer.parseInt(newPort));
233             }
234             catch (final Exception expected) {
235                 // back to string
236             }
237         }
238         else {
239             url_ = UrlUtils.getUrlWithNewHost(url_, newHost);
240         }
241 
242         url_ = UrlUtils.removeRedundantPort(url_);
243     }
244 
245     /**
246      * Returns the hostname portion of the URL.
247      *
248      * @return the hostname
249      */
250     @JsxGetter
251     public String getHostname() {
252         if (url_ == null) {
253             return null;
254         }
255 
256         return UrlUtils.encodeAnchor(url_.getHost());
257     }
258 
259     /**
260      * Sets the {@code hostname} property.
261      *
262      * @param hostname the new hostname value
263      */
264     @JsxSetter
265     public void setHostname(final String hostname) {
266         if (org.htmlunit.util.StringUtils.isEmptyOrNull(hostname) || hostname.indexOf(' ') > -1) {
267             return;
268         }
269 
270         final int idx = hostname.indexOf('#');
271         final String host = idx > -1 ? hostname.substring(0, idx) : hostname;
272         if (host.isEmpty()) {
273             return;
274         }
275 
276         try {
277             url_ = UrlUtils.getUrlWithNewHost(url_, host);
278         }
279         catch (final MalformedURLException  e) {
280             // do nothing
281         }
282     }
283 
284     /**
285      * Returns the full URL as a string.
286      *
287      * @return the full URL
288      */
289     @JsxGetter
290     public String getHref() {
291         if (url_ == null) {
292             return null;
293         }
294 
295         return jsToString();
296     }
297 
298     /**
299      * Sets the {@code href} property, navigating to the new URL.
300      *
301      * @param href the new URL string
302      * @throws MalformedURLException if the URL is malformed
303      */
304     @JsxSetter
305     public void setHref(final String href) throws MalformedURLException {
306         if (url_ == null) {
307             return;
308         }
309 
310         url_ = UrlUtils.toUrlUnsafe(href);
311         url_ = UrlUtils.removeRedundantPort(url_);
312     }
313 
314     /**
315      * Returns the origin of the URL.
316      *
317      * @return the origin
318      */
319     @JsxGetter
320     public Object getOrigin() {
321         if (url_ == null) {
322             return null;
323         }
324 
325         if (url_.getPort() < 0 || url_.getPort() == url_.getDefaultPort()) {
326             return url_.getProtocol() + "://" + url_.getHost();
327         }
328 
329         return url_.getProtocol() + "://" + url_.getHost() + ':' + url_.getPort();
330     }
331 
332     /**
333      * Returns a {@link URLSearchParams} object providing access to the decoded query arguments of the URL.
334      *
335      * @return the search params
336      */
337     @JsxGetter
338     public URLSearchParams getSearchParams() {
339         if (url_ == null) {
340             return null;
341         }
342 
343         final URLSearchParams searchParams = new URLSearchParams(this);
344         searchParams.setParentScope(getParentScope());
345         searchParams.setPrototype(getPrototype(searchParams.getClass()));
346         return searchParams;
347     }
348 
349     /**
350      * Returns the password specified before the domain name.
351      *
352      * @return the password, or an empty string if none is specified
353      */
354     @JsxGetter
355     public String getPassword() {
356         if (url_ == null) {
357             return null;
358         }
359 
360         final String userInfo = url_.getUserInfo();
361         if (userInfo != null) {
362             final int idx = userInfo.indexOf(':');
363             if (idx > -1) {
364                 return userInfo.substring(idx + 1);
365             }
366         }
367 
368         return "";
369     }
370 
371     /**
372      * Sets the {@code password} property.
373      *
374      * @param password the new password value
375      * @throws MalformedURLException if the resulting URL is malformed
376      */
377     @JsxSetter
378     public void setPassword(final String password) throws MalformedURLException {
379         if (url_ == null) {
380             return;
381         }
382 
383         url_ = UrlUtils.getUrlWithNewUserPassword(url_, password.isEmpty() ? null : password);
384     }
385 
386     /**
387      * Returns the pathname portion of the URL.
388      *
389      * @return the pathname
390      */
391     @JsxGetter
392     public String getPathname() {
393         if (url_ == null) {
394             return null;
395         }
396 
397         final String path = url_.getPath();
398         return path.isEmpty() ? "/" : path;
399     }
400 
401     /**
402      * Sets the {@code pathname} property.
403      *
404      * @param path the new pathname value
405      * @throws MalformedURLException if the resulting URL is malformed
406      */
407     @JsxSetter
408     public void setPathname(final String path) throws MalformedURLException {
409         if (url_ == null) {
410             return;
411         }
412 
413         url_ = UrlUtils.getUrlWithNewPath(url_, path.startsWith("/") ? path : "/" + path);
414     }
415 
416     /**
417      * Returns the port number of the URL, or an empty string if no explicit port is specified.
418      *
419      * @return the port, or an empty string
420      */
421     @JsxGetter
422     public String getPort() {
423         if (url_ == null) {
424             return null;
425         }
426 
427         final int port = url_.getPort();
428         return port == -1 ? "" : Integer.toString(port);
429     }
430 
431     /**
432      * Sets the {@code port} property.
433      *
434      * @param port the new port value, or an empty string to remove the port
435      * @throws MalformedURLException if the resulting URL is malformed
436      */
437     @JsxSetter
438     public void setPort(final String port) throws MalformedURLException {
439         if (url_ == null) {
440             return;
441         }
442         final int portInt = port.isEmpty() ? -1 : Integer.parseInt(port);
443         url_ = UrlUtils.getUrlWithNewPort(url_, portInt);
444         url_ = UrlUtils.removeRedundantPort(url_);
445     }
446 
447     /**
448      * Returns the protocol scheme of the URL, including the trailing {@code :}.
449      *
450      * @return the protocol
451      */
452     @JsxGetter
453     public String getProtocol() {
454         if (url_ == null) {
455             return null;
456         }
457         final String protocol = url_.getProtocol();
458         return protocol.isEmpty() ? "" : (protocol + ":");
459     }
460 
461     /**
462      * Sets the {@code protocol} property.
463      *
464      * @param protocol the new protocol value
465      * @throws MalformedURLException if the resulting URL is malformed
466      */
467     @JsxSetter
468     public void setProtocol(final String protocol) throws MalformedURLException {
469         if (url_ == null || protocol.isEmpty()) {
470             return;
471         }
472 
473         final java.net.URL newUrl = UrlUtils.getUrlWithNewProtocolLikeSetter(url_, protocol, fileWithoutHost());
474         if (newUrl != null) {
475             url_ = newUrl;
476         }
477     }
478 
479     /**
480      * Returns the query string, containing a {@code ?} followed by the URL's parameters.
481      *
482      * @return the search string, or an empty string if none
483      */
484     @JsxGetter
485     public String getSearch() {
486         if (url_ == null) {
487             return null;
488         }
489         final String search = url_.getQuery();
490         return search == null ? "" : "?" + search;
491     }
492 
493     /**
494      * Sets the {@code search} property.
495      *
496      * @param search the new search string
497      * @throws MalformedURLException if the resulting URL is malformed
498      */
499     @JsxSetter
500     public void setSearch(final String search) throws MalformedURLException {
501         if (url_ == null) {
502             return;
503         }
504 
505         String query;
506         if (search == null
507                 || org.htmlunit.util.StringUtils.equalsChar('?', search)
508                 || org.htmlunit.util.StringUtils.isEmptyString(search)) {
509             query = null;
510         }
511         else {
512             if (search.charAt(0) == '?') {
513                 query = search.substring(1);
514             }
515             else {
516                 query = search;
517             }
518             query = UrlUtils.encodeQuery(query);
519         }
520 
521         url_ = UrlUtils.getUrlWithNewQuery(url_, query);
522     }
523 
524     /**
525      * Sets the {@code search} property from a list of {@link NameValuePair}s.
526      *
527      * @param nameValuePairs the pairs to encode as the query string
528      * @throws MalformedURLException if the resulting URL is malformed
529      */
530     public void setSearch(final List<NameValuePair> nameValuePairs) throws MalformedURLException {
531         final StringBuilder newSearch = new StringBuilder();
532         for (final NameValuePair nameValuePair : nameValuePairs) {
533             if (newSearch.length() > 0) {
534                 newSearch.append('&');
535             }
536             newSearch
537                 .append(UrlUtils.encodeQueryPart(nameValuePair.getName()))
538                 .append('=')
539                 .append(UrlUtils.encodeQueryPart(nameValuePair.getValue()));
540         }
541 
542         url_ = UrlUtils.getUrlWithNewQuery(url_, newSearch.toString());
543     }
544 
545     /**
546      * Returns the username specified before the domain name.
547      *
548      * @return the username, or an empty string if none is specified
549      */
550     @JsxGetter
551     public String getUsername() {
552         if (url_ == null) {
553             return null;
554         }
555 
556         final String userInfo = url_.getUserInfo();
557         if (userInfo == null) {
558             return "";
559         }
560 
561         return StringUtils.substringBefore(userInfo, ':');
562     }
563 
564     /**
565      * Sets the {@code username} property.
566      *
567      * @param username the new username value
568      * @throws MalformedURLException if the resulting URL is malformed
569      */
570     @JsxSetter
571     public void setUsername(final String username) throws MalformedURLException {
572         if (url_ == null) {
573             return;
574         }
575         url_ = UrlUtils.getUrlWithNewUserName(url_, username.isEmpty() ? null : username);
576     }
577 
578     /**
579      * Returns the default string representation of this URL.
580      *
581      * @param hint the type hint
582      * @return the URL as a string
583      * @see org.htmlunit.javascript.HtmlUnitScriptable#getDefaultValue(java.lang.Class)
584      */
585     @Override
586     public Object getDefaultValue(final Class<?> hint) {
587         if (url_ == null) {
588             return super.getDefaultValue(hint);
589         }
590 
591         if (org.htmlunit.util.StringUtils.isEmptyOrNull(url_.getPath())) {
592             return url_.toExternalForm() + "/";
593         }
594         return url_.toExternalForm();
595     }
596 
597     /**
598      * Returns a serialized version of the URL. In practice this is equivalent to {@link #jsToString()}.
599      *
600      * @return the serialized URL string
601      */
602     @JsxFunction
603     public String toJSON() {
604         return jsToString();
605     }
606 
607     /**
608      * Returns the URL as a string.
609      *
610      * @return the URL string
611      */
612     @JsxFunction(functionName = "toString")
613     public String jsToString() {
614         if (org.htmlunit.util.StringUtils.isEmptyOrNull(url_.getPath())) {
615             try {
616                 return UrlUtils.serialize(UrlUtils.getUrlWithNewPath(url_, "/"));
617             }
618             catch (final MalformedURLException e) {
619                 return UrlUtils.serialize(url_);
620             }
621         }
622         return UrlUtils.serialize(url_);
623     }
624 
625     private boolean fileWithoutHost() {
626         // the browser version is not available for internal instances without scope (e.g. of URLSearchParams)
627         final BrowserVersion browserVersion = getBrowserVersion();
628         return browserVersion != null && browserVersion.hasFeature(JS_URL_FILE_WITHOUT_HOST);
629     }
630 }