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 java.nio.charset.StandardCharsets.UTF_8;
18  import static org.htmlunit.BrowserVersionFeatures.JS_NAVIGATOR_DO_NOT_TRACK_UNSPECIFIED;
19  import static org.htmlunit.javascript.configuration.SupportedBrowser.CHROME;
20  import static org.htmlunit.javascript.configuration.SupportedBrowser.EDGE;
21  import static org.htmlunit.javascript.configuration.SupportedBrowser.FF;
22  import static org.htmlunit.javascript.configuration.SupportedBrowser.FF_ESR;
23  
24  import java.io.IOException;
25  import java.net.MalformedURLException;
26  import java.net.URL;
27  import java.util.ArrayList;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.htmlunit.FormEncodingType;
32  import org.htmlunit.HttpHeader;
33  import org.htmlunit.HttpMethod;
34  import org.htmlunit.WebClient;
35  import org.htmlunit.WebRequest;
36  import org.htmlunit.WebRequest.HttpHint;
37  import org.htmlunit.WebResponse;
38  import org.htmlunit.WebWindow;
39  import org.htmlunit.corejs.javascript.Scriptable;
40  import org.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView;
41  import org.htmlunit.html.HtmlPage;
42  import org.htmlunit.html.csp.ContentSecurityPolicy;
43  import org.htmlunit.javascript.HtmlUnitScriptable;
44  import org.htmlunit.javascript.JavaScriptEngine;
45  import org.htmlunit.javascript.configuration.JsxClass;
46  import org.htmlunit.javascript.configuration.JsxConstructor;
47  import org.htmlunit.javascript.configuration.JsxFunction;
48  import org.htmlunit.javascript.configuration.JsxGetter;
49  import org.htmlunit.javascript.host.fetch.CorsLoader;
50  import org.htmlunit.javascript.host.file.Blob;
51  import org.htmlunit.javascript.host.geo.Geolocation;
52  import org.htmlunit.javascript.host.media.MediaDevices;
53  import org.htmlunit.javascript.host.network.NetworkInformation;
54  // TODO verify actual package - not visible from XMLHttpRequest.java's import list,
55  // which suggests it may already share a package with XMLHttpRequest rather than
56  // living here; adjust this import (and the FormData branch below) accordingly.
57  import org.htmlunit.javascript.host.xml.FormData;
58  import org.htmlunit.util.StringUtils;
59  import org.htmlunit.util.UrlUtils;
60  
61  /**
62   * JavaScript host object for {@code Navigator}.
63   *
64   * @author Mike Bowler
65   * @author Daniel Gredler
66   * @author Chris Erskine
67   * @author Ahmed Ashour
68   * @author Marc Guillemot
69   * @author Frank Danek
70   * @author Ronald Brill
71   *
72   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator">MDN Documentation</a>
73   */
74  @JsxClass
75  public class Navigator extends HtmlUnitScriptable {
76  
77      private static final Log LOG = LogFactory.getLog(Navigator.class);
78  
79      private PluginArray plugins_;
80      private MimeTypeArray mimeTypes_;
81      private MediaDevices mediaDevices_;
82  
83      /**
84       * Creates an instance of this object.
85       */
86      @JsxConstructor
87      public void jsConstructor() {
88          // nothing to do
89      }
90  
91      /**
92       * Returns the {@code appCodeName} property.
93       *
94       * @return the {@code appCodeName} property
95       */
96      @JsxGetter
97      public String getAppCodeName() {
98          return getBrowserVersion().getApplicationCodeName();
99      }
100 
101     /**
102      * Returns the {@code appName} property.
103      *
104      * @return the {@code appName} property
105      */
106     @JsxGetter
107     public String getAppName() {
108         return getBrowserVersion().getApplicationName();
109     }
110 
111     /**
112      * Returns the {@code appVersion} property.
113      *
114      * @return the {@code appVersion} property
115      */
116     @JsxGetter
117     public String getAppVersion() {
118         return getBrowserVersion().getApplicationVersion();
119     }
120 
121     /**
122      * Returns the language of the browser.
123      *
124      * @return the browser language
125      */
126     @JsxGetter
127     public String getLanguage() {
128         return getBrowserVersion().getBrowserLanguage();
129     }
130 
131     /**
132      * Returns the preferred languages of the browser as an array.
133      *
134      * @return the languages array
135      */
136     @JsxGetter
137     public Scriptable getLanguages() {
138         final String acceptLang = getBrowserVersion().getAcceptLanguageHeader();
139         if (StringUtils.isEmptyOrNull(acceptLang)) {
140             return JavaScriptEngine.newArray(getParentScope(), 0);
141         }
142 
143         final ArrayList<String> res = new ArrayList<>();
144         final String[] parts = StringUtils.splitAtComma(acceptLang);
145         for (final String part : parts) {
146             if (!StringUtils.isEmptyOrNull(part)) {
147                 final String lang = StringUtils.substringBefore(part, ";").trim();
148                 if (!StringUtils.isEmptyOrNull(part)) {
149                     res.add(lang);
150                 }
151             }
152         }
153 
154         return JavaScriptEngine.newArray(getParentScope(), res.toArray());
155     }
156 
157     /**
158      * Returns the {@code cookieEnabled} property.
159      *
160      * @return the {@code cookieEnabled} property
161      */
162     @JsxGetter
163     public boolean isCookieEnabled() {
164         return getWindow().getWebWindow().getWebClient().getCookieManager().isCookiesEnabled();
165     }
166 
167     /**
168      * Returns the {@code onLine} property.
169      *
170      * @return the {@code onLine} property
171      */
172     @JsxGetter
173     public boolean isOnLine() {
174         return getBrowserVersion().isOnLine();
175     }
176 
177     /**
178      * Returns the {@code platform} property.
179      *
180      * @return the {@code platform} property
181      */
182     @JsxGetter
183     public String getPlatform() {
184         return getBrowserVersion().getPlatform();
185     }
186 
187     /**
188      * Returns the {@code product} property.
189      *
190      * @return the {@code product} property
191      */
192     @JsxGetter
193     public String getProduct() {
194         return "Gecko";
195     }
196 
197     /**
198      * Returns the build number of the current browser.
199      *
200      * @return the {@code productSub} property
201      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/productSub">MDN Documentation</a>
202      */
203     @JsxGetter
204     public String getProductSub() {
205         return getBrowserVersion().getProductSub();
206     }
207 
208     /**
209      * Returns the {@code userAgent} property.
210      *
211      * @return the {@code userAgent} property
212      */
213     @JsxGetter
214     public String getUserAgent() {
215         return getBrowserVersion().getUserAgent();
216     }
217 
218     /**
219      * Returns the list of browser plugins.
220      *
221      * @return the {@code plugins} array
222      */
223     @JsxGetter
224     public PluginArray getPlugins() {
225         initPluginsAndMimeTypes();
226         return plugins_;
227     }
228 
229     private void initPluginsAndMimeTypes() {
230         // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/plugins
231         // Recent versions of the specification hard-code the returned list.
232         // If inline viewing of PDF files is supported the property lists five standard plugins.
233         // If inline PDF viewing is not supported then an empty list is returned.
234         if (plugins_ != null) {
235             return;
236         }
237         plugins_ = new PluginArray();
238         plugins_.setParentScope(getParentScope());
239         plugins_.setPrototype(getPrototype(PluginArray.class));
240 
241         Plugin plugin = new Plugin("PDF Viewer", "Portable Document Format", "internal-pdf-viewer");
242         plugin.setParentScope(getParentScope());
243         plugin.setPrototype(getPrototype(Plugin.class));
244 
245         // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mimeTypes
246         // Recent versions of the specification hard-code the returned set of MIME types.
247         // If PDF files can be displayed inline then application/pdf and text/pdf are listed,
248         // otherwise an empty list is returned.
249         mimeTypes_ = new MimeTypeArray();
250         mimeTypes_.setParentScope(getParentScope());
251         mimeTypes_.setPrototype(getPrototype(MimeTypeArray.class));
252 
253         final MimeType mimeTypeAppPdf = new MimeType("application/pdf", "Portable Document Format", "pdf", plugin);
254         mimeTypeAppPdf.setParentScope(getParentScope());
255         mimeTypeAppPdf.setPrototype(getPrototype(MimeType.class));
256         mimeTypes_.add(mimeTypeAppPdf);
257 
258         final MimeType mimeTypeTxtPdf = new MimeType("text/pdf", "Portable Document Format", "pdf", plugin);
259         mimeTypeTxtPdf.setParentScope(getParentScope());
260         mimeTypeTxtPdf.setPrototype(getPrototype(MimeType.class));
261         mimeTypes_.add(mimeTypeTxtPdf);
262 
263         plugin.add(mimeTypeAppPdf);
264         plugin.add(mimeTypeTxtPdf);
265         plugins_.add(plugin);
266 
267         // all the others
268         plugin = new Plugin("Chrome PDF Viewer", "Portable Document Format", "internal-pdf-viewer");
269         plugin.setParentScope(getParentScope());
270         plugin.setPrototype(getPrototype(Plugin.class));
271         plugin.add(mimeTypeAppPdf);
272         plugin.add(mimeTypeTxtPdf);
273         plugins_.add(plugin);
274 
275         plugin = new Plugin("Chromium PDF Viewer", "Portable Document Format", "internal-pdf-viewer");
276         plugin.setParentScope(getParentScope());
277         plugin.setPrototype(getPrototype(Plugin.class));
278         plugin.add(mimeTypeAppPdf);
279         plugin.add(mimeTypeTxtPdf);
280         plugins_.add(plugin);
281 
282         plugin = new Plugin("Microsoft Edge PDF Viewer", "Portable Document Format", "internal-pdf-viewer");
283         plugin.setParentScope(getParentScope());
284         plugin.setPrototype(getPrototype(Plugin.class));
285         plugin.add(mimeTypeAppPdf);
286         plugin.add(mimeTypeTxtPdf);
287         plugins_.add(plugin);
288 
289         plugin = new Plugin("WebKit built-in PDF", "Portable Document Format", "internal-pdf-viewer");
290         plugin.setParentScope(getParentScope());
291         plugin.setPrototype(getPrototype(Plugin.class));
292         plugin.add(mimeTypeAppPdf);
293         plugin.add(mimeTypeTxtPdf);
294         plugins_.add(plugin);
295     }
296 
297     /**
298      * Returns the {@code mimeTypes} property.
299      *
300      * @return the {@code mimeTypes} property
301      */
302     @JsxGetter
303     public MimeTypeArray getMimeTypes() {
304         initPluginsAndMimeTypes();
305         return mimeTypes_;
306     }
307 
308     /**
309      * Returns whether Java is enabled. Always returns {@code false}.
310      *
311      * @return {@code false}
312      */
313     @JsxFunction
314     public boolean javaEnabled() {
315         return false;
316     }
317 
318     /**
319      * Returns {@code false} as data tainting support is not enabled in HtmlUnit.
320      *
321      * @return {@code false}
322      */
323     @JsxFunction({FF, FF_ESR})
324     public boolean taintEnabled() {
325         return false;
326     }
327 
328     /**
329      * Returns the {@code geolocation} property.
330      *
331      * @return the {@code geolocation} property
332      */
333     @JsxGetter
334     public Geolocation getGeolocation() {
335         final Geolocation geolocation = new Geolocation();
336         geolocation.setParentScope(getParentScope());
337         geolocation.setPrototype(getPrototype(geolocation.getClass()));
338         return geolocation;
339     }
340 
341     /**
342      * Returns whether the browser supports inline display of PDF files when navigating to them.
343      *
344      * @return {@code true} if inline PDF viewing is supported
345      */
346     @JsxGetter
347     public boolean isPdfViewerEnabled() {
348         return true;
349     }
350 
351     /**
352      * Returns the {@code buildID} property.
353      *
354      * @return the {@code buildID} property
355      */
356     @JsxGetter({FF, FF_ESR})
357     public String getBuildID() {
358         return getBrowserVersion().getBuildId();
359     }
360 
361     /**
362      * Returns the {@code vendor} property.
363      *
364      * @return the {@code vendor} property
365      */
366     @JsxGetter
367     public String getVendor() {
368         return getBrowserVersion().getVendor();
369     }
370 
371     /**
372      * Returns the {@code vendorSub} property.
373      *
374      * @return the {@code vendorSub} property
375      */
376     @JsxGetter
377     public String getVendorSub() {
378         return "";
379     }
380 
381     /**
382      * Returns the {@code doNotTrack} property.
383      *
384      * @return the {@code doNotTrack} property
385      */
386     @JsxGetter
387     public Object getDoNotTrack() {
388         final WebClient client = getWindow().getWebWindow().getWebClient();
389         if (client.getOptions().isDoNotTrackEnabled()) {
390             return 1;
391         }
392         if (client.getBrowserVersion().hasFeature(JS_NAVIGATOR_DO_NOT_TRACK_UNSPECIFIED)) {
393             return "unspecified";
394         }
395         return null;
396     }
397 
398     /**
399      * Returns the {@code oscpu} property.
400      *
401      * @return the {@code oscpu} property
402      */
403     @JsxGetter({FF, FF_ESR})
404     public String getOscpu() {
405         return "Windows NT 6.1";
406     }
407 
408     /**
409      * Returns the {@code connection} property.
410      *
411      * @return the {@code connection} property
412      */
413     @JsxGetter({CHROME, EDGE})
414     public NetworkInformation getConnection() {
415         final NetworkInformation networkInformation = new NetworkInformation();
416         networkInformation.setPrototype(getPrototype(networkInformation.getClass()));
417         networkInformation.setParentScope(getParentScope());
418         return networkInformation;
419     }
420 
421     /**
422      * Returns the {@code mediaDevices} property.
423      *
424      * @return the {@code mediaDevices} property
425      */
426     @JsxGetter
427     public MediaDevices getMediaDevices() {
428         if (mediaDevices_ == null) {
429             mediaDevices_ = new MediaDevices();
430             mediaDevices_.setPrototype(getPrototype(mediaDevices_.getClass()));
431             mediaDevices_.setParentScope(getParentScope());
432         }
433         return mediaDevices_;
434     }
435 
436     /**
437      * The {@code sendBeacon()} method.
438      * <p>
439      * Note: real browsers queue the beacon and return immediately, continuing to
440      * attempt delivery even after the page unloads. This implementation instead sends
441      * the request synchronously (mirroring how {@code HyperlinkElementSupport} already
442      * handles hyperlink-auditing/{@code ping} requests and swallows any network error,
443      * since there is no caller left to report it to by the time
444      * a real browser would encounter it either.
445      * </p>
446      *
447      * @param url the URL to send the data to
448      * @param data the data to send; USVString, {@link Blob}, {@link URLSearchParams},
449      *             {@code FormData}, and ArrayBufferView are supported, per spec
450      * @return {@code true} if the browser successfully queued the data for transfer,
451      *         {@code false} otherwise (e.g. the URL could not be resolved)
452      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">
453      *      MDN Documentation</a>
454      */
455     @JsxFunction
456     public boolean sendBeacon(final String url, final Object data) {
457         final Window window = getWindow();
458         final WebWindow webWindow = window.getWebWindow();
459         final HtmlPage page = (HtmlPage) webWindow.getEnclosedPage();
460         final URL pageUrl = page.getUrl();
461 
462         final URL targetUrl;
463         try {
464             // upgrade-insecure-requests of the Content-Security-Policy
465             targetUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, page.getFullyQualifiedUrl(url));
466         }
467         catch (final MalformedURLException e) {
468             if (LOG.isInfoEnabled()) {
469                 LOG.info("sendBeacon(): invalid url '" + url + "'", e);
470             }
471             return false;
472         }
473 
474         // like Chrome: a beacon blocked by the Content-Security-Policy is reported
475         // as queued (Firefox returns false)
476         if (!ContentSecurityPolicy.allowsConnection(page, targetUrl, targetUrl)) {
477             return true;
478         }
479 
480         final WebRequest request = new WebRequest(targetUrl, HttpMethod.POST);
481 
482         // a beacon is always a POST, so per Fetch's "Origin header" rules this is
483         // added unconditionally, same as HyperlinkElementSupport's ping request
484         try {
485             request.setRefererHeader(pageUrl);
486             request.setReferrerPolicy(page.getReferrerPolicy());
487             request.setAdditionalHeader(HttpHeader.ORIGIN,
488                     UrlUtils.getUrlWithProtocolAndAuthority(pageUrl).toExternalForm());
489         }
490         catch (final MalformedURLException e) {
491             if (LOG.isInfoEnabled()) {
492                 LOG.info("sendBeacon(): invalid origin url '" + pageUrl + "'", e);
493             }
494         }
495 
496         // Sec-Fetch-* support (https://www.w3.org/TR/fetch-metadata/): a beacon has no
497         // destination and is always no-cors, matching hyperlink-auditing (ping) requests.
498         request.setFetchDestination(WebRequest.FetchDestination.EMPTY);
499         request.setFetchModeOverride(WebRequest.FetchMode.NO_CORS);
500         request.setRequestingUrl(pageUrl);
501         request.setSiteForCookies(page.getSiteForCookiesUrl());
502 
503         fillRequestBody(request, data);
504 
505         final WebClient webClient = webWindow.getWebClient();
506         try {
507             // a body with a type that is not CORS-safelisted (e.g. a Blob of type application/json)
508             // makes the beacon a cors request with credentials; another origin has to allow it
509             // in the preflight before the request is sent (also for redirect targets)
510             if (CorsLoader.isPreflight(request)) {
511                 final CorsLoader loader = new CorsLoader(webWindow, CorsLoader.CredentialsMode.INCLUDE,
512                         CorsLoader.RedirectMode.FOLLOW, 0);
513                 final boolean sameOrigin = UrlUtils.isSameOrigin(pageUrl, targetUrl);
514                 if (!sameOrigin) {
515                     final WebResponse preflightResponse = loader.sendPreflight(request);
516                     if (!preflightResponse.isSuccessOrUseProxyOrNotModified()
517                             || !loader.isPreflightAuthorized(request, preflightResponse)) {
518                         if (LOG.isInfoEnabled()) {
519                             LOG.info("sendBeacon(): the preflight for '" + targetUrl + "' does not allow the request");
520                         }
521                         return true;
522                     }
523                 }
524                 loader.load(request, sameOrigin);
525             }
526             else {
527                 webClient.loadWebResponse(request);
528             }
529         }
530         catch (final IOException e) {
531             if (LOG.isInfoEnabled()) {
532                 LOG.info("sendBeacon(): request failed", e);
533             }
534             // per spec this still returns true - queuing succeeded even if delivery didn't
535         }
536         return true;
537     }
538 
539     /**
540      * Fills in the request body for {@link #sendBeacon(String, Object)}, dispatching on
541      * the data's type the same way {@code XMLHttpRequest#prepareRequestContent} does for
542      * the body types the Beacon spec actually allows (unlike XHR, this excludes
543      * {@code Document} types).
544      *
545      * @param request the request to fill in
546      * @param data the data passed to {@code sendBeacon()}, possibly {@code null}/undefined
547      */
548     private static void fillRequestBody(final WebRequest request, final Object data) {
549         if (data == null || JavaScriptEngine.isUndefined(data)) {
550             return;
551         }
552 
553         if (data instanceof FormData formData) {
554             formData.fillRequest(request);
555         }
556         else if (data instanceof URLSearchParams params) {
557             params.fillRequest(request);
558             request.setCharset(UTF_8);
559             request.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
560         }
561         else if (data instanceof Blob blob) {
562             blob.fillRequest(request);
563         }
564         else if (data instanceof NativeArrayBufferView view) {
565             request.setRequestBody(
566                 UTF_8.decode(
567                     view.getBuffer()
568                         .getByteBuffer()
569                         .position(view.getByteOffset())
570                         .limit(view.getByteOffset() + view.getByteLength())
571                 ).toString());
572             request.setEncodingType(null);
573         }
574         else {
575             final String body = JavaScriptEngine.toString(data);
576             if (!body.isEmpty()) {
577                 request.setRequestBody(body);
578                 request.setEncodingType(FormEncodingType.TEXT_PLAIN);
579                 request.setCharset(UTF_8);
580                 request.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
581             }
582         }
583     }
584 }