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_LOCATION_PROTOCOL_UNCHANGED_NO_NAVIGATION;
18  import static org.htmlunit.BrowserVersionFeatures.JS_LOCATION_RELOAD_REFERRER;
19  
20  import java.io.IOException;
21  import java.lang.reflect.Method;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.htmlunit.BrowserVersion;
28  import org.htmlunit.Page;
29  import org.htmlunit.WebClient;
30  import org.htmlunit.WebRequest;
31  import org.htmlunit.WebWindow;
32  import org.htmlunit.corejs.javascript.Context;
33  import org.htmlunit.corejs.javascript.Function;
34  import org.htmlunit.corejs.javascript.FunctionObject;
35  import org.htmlunit.corejs.javascript.ScriptableObject;
36  import org.htmlunit.corejs.javascript.VarScope;
37  import org.htmlunit.html.FrameWindow;
38  import org.htmlunit.html.HtmlPage;
39  import org.htmlunit.html.csp.ContentSecurityPolicy;
40  import org.htmlunit.javascript.HtmlUnitScriptable;
41  import org.htmlunit.javascript.JavaScriptEngine;
42  import org.htmlunit.javascript.configuration.JsxClass;
43  import org.htmlunit.javascript.configuration.JsxConstructor;
44  import org.htmlunit.javascript.host.dom.DOMException;
45  import org.htmlunit.javascript.host.event.Event;
46  import org.htmlunit.javascript.host.event.HashChangeEvent;
47  import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
48  import org.htmlunit.util.StringUtils;
49  import org.htmlunit.util.UrlUtils;
50  
51  /**
52   * JavaScript host object for {@code Location}.
53   *
54   * @author Mike Bowler
55   * @author Michael Ottati
56   * @author Marc Guillemot
57   * @author Chris Erskine
58   * @author Daniel Gredler
59   * @author David K. Taylor
60   * @author Ahmed Ashour
61   * @author Ronald Brill
62   * @author Frank Danek
63   * @author Adam Afeltowicz
64   * @author Atsushi Nakagawa
65   * @author Lai Quang Duong
66   * @author Kanoko Yamamoto
67   *
68   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location">MDN Documentation</a>
69   */
70  @JsxClass
71  public class Location extends HtmlUnitScriptable {
72  
73      private static final Log LOG = LogFactory.getLog(Location.class);
74      private static final String UNKNOWN = "null";
75  
76      /**
77       * The window which owns this location object.
78       */
79      private Window window_;
80  
81      private static final Method METHOD_ASSIGN;
82      private static final Method METHOD_RELOAD;
83      private static final Method METHOD_REPLACE;
84      private static final Method METHOD_TO_STRING;
85  
86      private static final Method GETTER_HASH;
87      private static final Method SETTER_HASH;
88  
89      private static final Method GETTER_HOST;
90      private static final Method SETTER_HOST;
91  
92      private static final Method GETTER_HOSTNAME;
93      private static final Method SETTER_HOSTNAME;
94  
95      private static final Method GETTER_HREF;
96      private static final Method SETTER_HREF;
97  
98      private static final Method GETTER_ORIGIN;
99  
100     private static final Method GETTER_PATHNAME;
101     private static final Method SETTER_PATHNAME;
102 
103     private static final Method GETTER_PORT;
104     private static final Method SETTER_PORT;
105 
106     private static final Method GETTER_PROTOCOL;
107     private static final Method SETTER_PROTOCOL;
108 
109     private static final Method GETTER_SEARCH;
110     private static final Method SETTER_SEARCH;
111 
112     static {
113         try {
114             METHOD_ASSIGN = Location.class.getDeclaredMethod("assign", String.class);
115             METHOD_RELOAD = Location.class.getDeclaredMethod("reload", boolean.class);
116             METHOD_REPLACE = Location.class.getDeclaredMethod("replace", String.class);
117             METHOD_TO_STRING = Location.class.getDeclaredMethod("jsToString");
118 
119             GETTER_HASH = Location.class.getDeclaredMethod("getHash");
120             SETTER_HASH = Location.class.getDeclaredMethod("setHash", String.class);
121 
122             GETTER_HOST = Location.class.getDeclaredMethod("getHost");
123             SETTER_HOST = Location.class.getDeclaredMethod("setHost", String.class);
124 
125             GETTER_HOSTNAME = Location.class.getDeclaredMethod("getHostname");
126             SETTER_HOSTNAME = Location.class.getDeclaredMethod("setHostname", String.class);
127 
128             GETTER_HREF = Location.class.getDeclaredMethod("getHref");
129             SETTER_HREF = Location.class.getDeclaredMethod("setHref", String.class);
130 
131             GETTER_ORIGIN = Location.class.getDeclaredMethod("getOrigin");
132 
133             GETTER_PATHNAME = Location.class.getDeclaredMethod("getPathname");
134             SETTER_PATHNAME = Location.class.getDeclaredMethod("setPathname", String.class);
135 
136             GETTER_PORT = Location.class.getDeclaredMethod("getPort");
137             SETTER_PORT = Location.class.getDeclaredMethod("setPort", String.class);
138 
139             GETTER_PROTOCOL = Location.class.getDeclaredMethod("getProtocol");
140             SETTER_PROTOCOL = Location.class.getDeclaredMethod("setProtocol", String.class);
141 
142             GETTER_SEARCH = Location.class.getDeclaredMethod("getSearch");
143             SETTER_SEARCH = Location.class.getDeclaredMethod("setSearch", String.class);
144         }
145         catch (NoSuchMethodException | SecurityException e) {
146             throw new RuntimeException(e);
147         }
148     }
149 
150     /**
151      * The current hash; cached locally to avoid modifying the page's URL and
152      * forcing a page reload each time this changes.
153      */
154     private String hash_;
155 
156     /**
157      * Creates an instance of this object.
158      *
159      * @param cx the current context
160      * @param scope the scope
161      * @param args the constructor arguments
162      * @param ctorObj the function object
163      * @param inNewExpr whether invoked via {@code new}
164      * @return the new {@code Location} instance
165      */
166     @JsxConstructor
167     public static Location jsConstructor(final Context cx, final VarScope scope,
168             final Object[] args, final Function ctorObj, final boolean inNewExpr) {
169 
170         final Location location = new Location();
171         location.setParentScope(scope);
172         location.setPrototype(((FunctionObject) ctorObj).getClassPrototype());
173 
174         location.initialize(scope, null, null);
175 
176         return location;
177     }
178 
179     /**
180      * Initializes this {@code Location}.
181      *
182      * @param scope the scope
183      * @param window the window that this location belongs to
184      * @param page the page that will become the enclosing page
185      */
186     public void initialize(final VarScope scope, final Window window, final Page page) {
187         final int attributes = ScriptableObject.PERMANENT | ScriptableObject.READONLY;
188 
189         FunctionObject functionObject = new FunctionObject(METHOD_ASSIGN.getName(), METHOD_ASSIGN, scope);
190         defineProperty(METHOD_ASSIGN.getName(), functionObject, attributes);
191 
192         functionObject = new FunctionObject(METHOD_RELOAD.getName(), METHOD_RELOAD, scope);
193         defineProperty(METHOD_RELOAD.getName(), functionObject, attributes);
194 
195         functionObject = new FunctionObject(METHOD_REPLACE.getName(), METHOD_REPLACE, scope);
196         defineProperty(METHOD_REPLACE.getName(), functionObject, attributes);
197 
198         functionObject = new FunctionObject(METHOD_TO_STRING.getName(), METHOD_TO_STRING, scope);
199         defineProperty("toString", functionObject, attributes);
200 
201         defineProperty(scope, "hash", null, GETTER_HASH, SETTER_HASH, attributes);
202         defineProperty(scope, "host", null, GETTER_HOST, SETTER_HOST, attributes);
203         defineProperty(scope, "hostname", null, GETTER_HOSTNAME, SETTER_HOSTNAME, attributes);
204         defineProperty(scope, "href", null, GETTER_HREF, SETTER_HREF, attributes);
205         defineProperty(scope, "origin", null, GETTER_ORIGIN, null, attributes);
206         defineProperty(scope, "pathname", null, GETTER_PATHNAME, SETTER_PATHNAME, attributes);
207         defineProperty(scope, "port", null, GETTER_PORT, SETTER_PORT, attributes);
208         defineProperty(scope, "protocol", null, GETTER_PROTOCOL, SETTER_PROTOCOL, attributes);
209         defineProperty(scope, "search", null, GETTER_SEARCH, SETTER_SEARCH, attributes);
210 
211         window_ = window;
212         if (window_ != null && page != null) {
213             setHash(null, page.getUrl().getRef());
214         }
215     }
216 
217     /**
218      * {@inheritDoc}
219      */
220     @Override
221     public Object getDefaultValue(final Class<?> hint) {
222         if (getPrototype() != null
223                 && window_ != null
224                 && (hint == null || String.class.equals(hint))) {
225             return getHref();
226         }
227         return super.getDefaultValue(hint);
228     }
229 
230     /**
231      * Loads the new HTML document corresponding to the specified URL.
232      *
233      * @param url the URL of the new HTML document to load
234      * @throws IOException if loading the specified location fails
235      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/assign">MDN Documentation</a>
236      */
237     public void assign(final String url) throws IOException {
238         setHref(url);
239     }
240 
241     /**
242      * Reloads the current page, optionally forcing retrieval from the server even if
243      * the browser cache contains the latest version of the document.
244      *
245      * @param force if {@code true}, force reload from the server; otherwise, the browser may reload from cache
246      * @throws IOException if there is a problem reloading the page
247      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/reload">MDN Documentation</a>
248      */
249     public void reload(final boolean force) throws IOException {
250         final WebWindow webWindow = window_.getWebWindow();
251         final HtmlPage htmlPage = (HtmlPage) webWindow.getEnclosedPage();
252         final WebRequest request = htmlPage.getWebResponse().getWebRequest();
253 
254         // update request url with location.href in case hash was changed;
255         // toUrlUnsafe() supports the about: urls (e.g. about:srcdoc)
256         request.setUrl(UrlUtils.toUrlUnsafe(getHref()));
257         if (getBrowserVersion().hasFeature(JS_LOCATION_RELOAD_REFERRER)) {
258             request.setRefererHeader(htmlPage.getUrl());
259             request.setReferrerPolicy(htmlPage.getReferrerPolicy());
260         }
261 
262         webWindow.getWebClient().download(webWindow, "", request, false, null, "JS location.reload");
263     }
264 
265     /**
266      * Loads the document at the specified URL, replacing the current entry in the session history
267      * so that the previous page cannot be reached via the back button.
268      *
269      * @param url the new URL to load
270      * @throws IOException if loading the specified location fails
271      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/replace">MDN Documentation</a>
272      */
273     public void replace(final String url) throws IOException {
274         window_.getWebWindow().getHistory().removeCurrent();
275         setHref(url);
276     }
277 
278     /**
279      * Returns the location URL as a string.
280      *
281      * @return the location URL
282      */
283     public String jsToString() {
284         if (window_ != null) {
285             return getHref();
286         }
287         return "";
288     }
289 
290     /**
291      * Returns the full URL of the current page.
292      *
293      * @return the location URL
294      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/href">MDN Documentation</a>
295      */
296     public String getHref() {
297         final WebWindow webWindow = window_.getWebWindow();
298         final Page page = webWindow.getEnclosedPage();
299         if (page == null) {
300             return UNKNOWN;
301         }
302         try {
303             URL url = page.getUrl();
304             if (url.getUserInfo() != null) {
305                 // like the browsers, location never contains the credentials (document.URL does)
306                 url = UrlUtils.getUrlWithoutUserInfo(url);
307             }
308             final String hash = getHash(true);
309             if (hash != null) {
310                 url = UrlUtils.getUrlWithNewRef(url, hash);
311             }
312             String s = url.toExternalForm();
313             if (s.startsWith("file:/") && !s.startsWith("file:///")) {
314                 // Java (sometimes?) returns file URLs with a single slash; however, browsers return
315                 // three slashes. See http://www.cyanwerks.com/file-url-formats.html for more info.
316                 s = "file:///" + s.substring("file:/".length());
317             }
318             return s;
319         }
320         catch (final MalformedURLException e) {
321             if (LOG.isErrorEnabled()) {
322                 LOG.error(e.getMessage(), e);
323             }
324             return page.getUrl().toExternalForm();
325         }
326     }
327 
328     /**
329      * Sets the location URL to an entirely new value, navigating to the new page.
330      *
331      * @param newLocation the new location URL
332      * @throws IOException if loading the specified location fails
333      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/href">MDN Documentation</a>
334      */
335     public void setHref(final String newLocation) throws IOException {
336         if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
337             final String script = newLocation.substring(11);
338             final HtmlPage page = (HtmlPage) window_.getWebWindow().getEnclosedPage();
339             if (ContentSecurityPolicy.allowsJavaScriptUrl(page, null, newLocation)) {
340                 page.executeJavaScript(script, "new location value", 1);
341             }
342             return;
343         }
344 
345         try {
346             // we need to get the caller window to get the calling page
347             WebWindow webWindow = ((Window) JavaScriptEngine.getTopCallScope().getGlobalThis()).getWebWindow();
348             final HtmlPage callingPage = (HtmlPage) webWindow.getEnclosedPage();
349             checkSandboxedNavigation(callingPage, webWindow, window_.getWebWindow());
350 
351             final BrowserVersion browserVersion = webWindow.getWebClient().getBrowserVersion();
352 
353             URL url = callingPage.getFullyQualifiedUrl(newLocation);
354             // fix for empty url
355             if (StringUtils.isEmptyOrNull(newLocation)) {
356                 url = UrlUtils.getUrlWithNewRef(url, null);
357             }
358             url = upgradeInsecureRequest(callingPage, window_.getWebWindow(), url);
359 
360             // accessing to local resource is forbidden for security reason
361             if (!callingPage.isLocalResourceAccessAllowed(url)) {
362                 webWindow.getWebClient().getIncorrectnessListener()
363                         .notify("Not allowed to load local resource: " + url, this);
364                 return;
365             }
366 
367             final WebRequest webRequest = new WebRequest(url,
368                         browserVersion.getHtmlAcceptHeader(), browserVersion.getAcceptEncodingHeader());
369             webRequest.setRefererHeader(callingPage.getUrl());
370             webRequest.setReferrerPolicy(callingPage.getReferrerPolicy());
371 
372             webRequest.markAsNavigation(getUrl(), false);
373             webRequest.setFetchModeOverride(WebRequest.FetchMode.NAVIGATE);
374             upgradeInsecureRedirects(callingPage, window_.getWebWindow(), webRequest);
375 
376             webWindow = window_.getWebWindow();
377             webWindow.getWebClient().download(webWindow, "", webRequest, true, null, "JS set location");
378         }
379         catch (final MalformedURLException e) {
380             if (LOG.isErrorEnabled()) {
381                 LOG.error("setHref('" + newLocation + "') got MalformedURLException", e);
382             }
383             throw e;
384         }
385     }
386 
387     /**
388      * A sandboxed document is only allowed to navigate its own window and the windows of its
389      * descendants; the top window only with 'allow-top-navigation'.
390      *
391      * @param callingPage the page navigating
392      * @param callingWindow the window of the calling page
393      * @param targetWindow the window to be navigated
394      */
395     private void checkSandboxedNavigation(final HtmlPage callingPage, final WebWindow callingWindow,
396             final WebWindow targetWindow) {
397         if (callingPage.getSandboxTokens() == null) {
398             return;
399         }
400 
401         // the window itself or a descendant
402         WebWindow window = targetWindow;
403         while (true) {
404             if (window == callingWindow) {
405                 return;
406             }
407             final WebWindow parent = window.getParentWindow();
408             if (parent == null || parent == window) {
409                 break;
410             }
411             window = parent;
412         }
413 
414         if (targetWindow == callingWindow.getTopWindow()
415                 && callingPage.isSandboxAllowed("allow-top-navigation")) {
416             return;
417         }
418 
419         throw JavaScriptEngine.asJavaScriptException(window_,
420                 "The document is sandboxed and lacks the 'allow-top-navigation' flag.",
421                 DOMException.SECURITY_ERR);
422     }
423 
424     /**
425      * Returns the search portion of the location URL (the portion following the {@code ?}).
426      *
427      * @return the search portion of the location URL
428      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/search">MDN Documentation</a>
429      */
430     public String getSearch() {
431         final URL url = getUrl();
432         final String search = url.getQuery();
433         if (StringUtils.isEmptyOrNull(search)) {
434             return "";
435         }
436         return "?" + search;
437     }
438 
439     /**
440      * Sets the search portion of the location URL (the portion following the {@code ?}).
441      *
442      * @param search the new search portion of the location URL
443      * @throws Exception if an error occurs
444      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/search">MDN Documentation</a>
445      */
446     public void setSearch(final String search) throws Exception {
447         setUrl(UrlUtils.getUrlWithNewQuery(getUrl(), search));
448     }
449 
450     /**
451      * Returns the hash portion of the location URL (the portion following the {@code #}).
452      *
453      * @return the hash portion of the location URL
454      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hash">MDN Documentation</a>
455      */
456     public String getHash() {
457         if (StringUtils.isEmptyOrNull(hash_)) {
458             return "";
459         }
460 
461         if (hash_.indexOf('%') == -1) {
462             return "#" + UrlUtils.encodeHash(hash_);
463         }
464         return "#" + UrlUtils.encodeHash(UrlUtils.decode(hash_));
465     }
466 
467     private String getHash(final boolean encoded) {
468         if (hash_ == null || hash_.isEmpty()) {
469             return null;
470         }
471         if (encoded) {
472             return UrlUtils.encodeHash(hash_);
473         }
474         return hash_;
475     }
476 
477     /**
478      * Sets the hash portion of the location URL (the portion following the {@code #}).
479      * This method does not cause a server hit.
480      *
481      * @param hash the new hash portion of the location URL
482      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hash">MDN Documentation</a>
483      */
484     public void setHash(final String hash) {
485         // IMPORTANT: This method must not call setUrl(), because
486         // we must not hit the server just to change the hash!
487         setHash(getHref(), hash, true);
488     }
489 
490     /**
491      * Sets the hash portion of the location URL (the portion following the {@code #}).
492      *
493      * @param oldURL the old URL
494      * @param hash the new hash portion of the location URL
495      */
496     public void setHash(final String oldURL, final String hash) {
497         setHash(oldURL, hash, true);
498     }
499 
500     /**
501      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
502      *
503      * Sets the hash portion of the location URL (the portion following the {@code #}).
504      *
505      * @param oldURL the old URL
506      * @param hash the new hash portion of the location URL
507      * @param triggerHashChanged option to disable event triggering
508      */
509     public void setHash(final String oldURL, final String hash, final boolean triggerHashChanged) {
510         // IMPORTANT: This method must not call setUrl(), because
511         // we must not hit the server just to change the hash!
512         final String newHash = hash != null && !hash.isEmpty() && hash.charAt(0) == '#'
513                                     ? hash.substring(1)
514                                     : hash;
515         final boolean hasChanged = newHash != null && !newHash.equals(hash_);
516         hash_ = newHash;
517 
518         if (hasChanged) {
519             final Window w = getWindow();
520             final Page page = w.getWebWindow().getEnclosedPage();
521             if (page != null) {
522                 final WebRequest request = page.getWebResponse().getWebRequest();
523                 request.setUrl(UrlUtils.toUrlSafe(getHref()));
524             }
525 
526             if (triggerHashChanged) {
527                 final Event event = new HashChangeEvent(w, Event.TYPE_HASH_CHANGE, oldURL, getHref());
528                 w.executeEventLocally(event);
529             }
530         }
531     }
532 
533     /**
534      * Returns the hostname portion of the location URL.
535      *
536      * @return the hostname portion of the location URL
537      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname">MDN Documentation</a>
538      */
539     public String getHostname() {
540         return getUrl().getHost();
541     }
542 
543     /**
544      * Sets the hostname portion of the location URL.
545      *
546      * @param hostname the new hostname portion of the location URL
547      * @throws Exception if an error occurs
548      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname">MDN Documentation</a>
549      */
550     public void setHostname(final String hostname) throws Exception {
551         setUrl(UrlUtils.getUrlWithNewHost(getUrl(), hostname));
552     }
553 
554     /**
555      * Returns the host portion of the location URL (the {@code [hostname]:[port]} portion).
556      *
557      * @return the host portion of the location URL
558      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/host">MDN Documentation</a>
559      */
560     public String getHost() {
561         final URL url = getUrl();
562         final int port = url.getPort();
563         final String host = url.getHost();
564 
565         if (port == -1) {
566             return host;
567         }
568         return host + ":" + port;
569     }
570 
571     /**
572      * Sets the host portion of the location URL (the {@code [hostname]:[port]} portion).
573      *
574      * @param host the new host portion of the location URL
575      * @throws Exception if an error occurs
576      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/host">MDN Documentation</a>
577      */
578     public void setHost(final String host) throws Exception {
579         final String hostname;
580         final int port;
581         final int index = host.indexOf(':');
582         if (index == -1) {
583             hostname = host;
584             port = -1;
585         }
586         else {
587             hostname = host.substring(0, index);
588             port = Integer.parseInt(host.substring(index + 1));
589         }
590         final URL url = UrlUtils.getUrlWithNewHostAndPort(getUrl(), hostname, port);
591         setUrl(url);
592     }
593 
594     /**
595      * Returns the pathname portion of the location URL.
596      *
597      * @return the pathname portion of the location URL
598      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname">MDN Documentation</a>
599      */
600     public String getPathname() {
601         if (UrlUtils.URL_ABOUT_BLANK == getUrl()) {
602             return "blank";
603         }
604         return getUrl().getPath();
605     }
606 
607     /**
608      * Sets the pathname portion of the location URL.
609      *
610      * @param pathname the new pathname portion of the location URL
611      * @throws Exception if an error occurs
612      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname">MDN Documentation</a>
613      */
614     public void setPathname(final String pathname) throws Exception {
615         setUrl(UrlUtils.getUrlWithNewPath(getUrl(), pathname));
616     }
617 
618     /**
619      * Returns the port portion of the location URL.
620      *
621      * @return the port portion of the location URL, or an empty string if no port is specified
622      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/port">MDN Documentation</a>
623      */
624     public String getPort() {
625         final int port = getUrl().getPort();
626         if (port == -1) {
627             return "";
628         }
629         return Integer.toString(port);
630     }
631 
632     /**
633      * Sets the port portion of the location URL.
634      *
635      * @param port the new port portion of the location URL
636      * @throws Exception if an error occurs
637      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/port">MDN Documentation</a>
638      */
639     public void setPort(final String port) throws Exception {
640         setUrl(UrlUtils.getUrlWithNewPort(getUrl(), Integer.parseInt(port)));
641     }
642 
643     /**
644      * Returns the protocol portion of the location URL, including the trailing {@code :}.
645      *
646      * @return the protocol portion of the location URL
647      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/protocol">MDN Documentation</a>
648      */
649     public String getProtocol() {
650         return getUrl().getProtocol() + ":";
651     }
652 
653     /**
654      * Sets the protocol portion of the location URL.
655      * Like the HTML Standard, an invalid scheme throws a SyntaxError and only http(s) urls are
656      * navigated (e.g. setting 'file:' or 'ftp:' does nothing); the URL Standard rules of the
657      * {@code protocol} setter apply (see {@link UrlUtils#getUrlWithNewProtocolLikeSetter(URL, String)}).
658      *
659      * @param protocol the new protocol portion of the location URL
660      * @throws Exception if an error occurs
661      * @see <a href="https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location-protocol">
662      *      HTML Standard - location.protocol</a>
663      */
664     public void setProtocol(final String protocol) throws Exception {
665         final URL url = getUrl();
666         final URL newUrl = UrlUtils.getUrlWithNewProtocolLikeSetter(url, protocol);
667         if (newUrl == null) {
668             throw JavaScriptEngine.asJavaScriptException(this,
669                     "Failed to set the 'protocol' property on 'Location': '" + protocol
670                     + "' is an invalid scheme.", DOMException.SYNTAX_ERR);
671         }
672         final String scheme = newUrl.getProtocol();
673         if (!"http".equals(scheme) && !"https".equals(scheme)) {
674             return;
675         }
676         if (newUrl == url
677                 && window_.getWebWindow().getWebClient().getBrowserVersion()
678                         .hasFeature(JS_LOCATION_PROTOCOL_UNCHANGED_NO_NAVIGATION)) {
679             // Firefox does not navigate if nothing was changed
680             return;
681         }
682         setUrl(newUrl);
683     }
684 
685     /**
686      * Returns this location's current URL.
687      *
688      * @return this location's current URL
689      */
690     private URL getUrl() {
691         return window_.getWebWindow().getEnclosedPage().getUrl();
692     }
693 
694     /**
695      * Upgrade-insecure-requests of the Content-Security-Policy; navigations of frames
696      * are always upgraded, top level navigations only for the host of the page.
697      */
698     private static URL upgradeInsecureRequest(final HtmlPage page, final WebWindow targetWindow, final URL url) {
699         if (targetWindow instanceof FrameWindow) {
700             return ContentSecurityPolicy.upgradeInsecureRequest(page, url);
701         }
702         return ContentSecurityPolicy.upgradeInsecureNavigation(page, url);
703     }
704 
705     private static void upgradeInsecureRedirects(final HtmlPage page, final WebWindow targetWindow,
706             final WebRequest webRequest) {
707         if (targetWindow instanceof FrameWindow) {
708             ContentSecurityPolicy.upgradeInsecureRedirects(page, webRequest);
709         }
710         else {
711             ContentSecurityPolicy.upgradeInsecureNavigationRedirects(page, webRequest);
712         }
713     }
714 
715     /**
716      * Sets this location's URL, triggering a server request and loading the resulting document
717      * into this location's window.
718      *
719      * @param url this location's new URL
720      * @throws IOException if there is a problem loading the new location
721      */
722     private void setUrl(final URL url) throws IOException {
723         final WebWindow webWindow = window_.getWebWindow();
724         final WebClient webClient = webWindow.getWebClient();
725         final BrowserVersion browserVersion = webClient.getBrowserVersion();
726 
727         URL requestUrl = url;
728         if (webWindow.getEnclosedPage() instanceof HtmlPage page) {
729             requestUrl = upgradeInsecureRequest(page, webWindow, url);
730         }
731 
732         // accessing to local resource is forbidden for security reason;
733         // like in setHref() the page of the running script decides, not the page shown in this window
734         final WebWindow callingWindow = ((Window) JavaScriptEngine.getTopCallScope().getGlobalThis()).getWebWindow();
735         final boolean allowed;
736         if (callingWindow.getEnclosedPage() instanceof HtmlPage callingPage) {
737             allowed = callingPage.isLocalResourceAccessAllowed(requestUrl);
738         }
739         else {
740             allowed = webClient.getOptions().isLocalFileAccessFromRemotePagesAllowed()
741                     || UrlUtils.isLocalResourceAccessAllowed(callingWindow.getEnclosedPage().getUrl(), requestUrl);
742         }
743         if (!allowed) {
744             webClient.getIncorrectnessListener().notify("Not allowed to load local resource: " + requestUrl, this);
745             return;
746         }
747 
748         final WebRequest webRequest = new WebRequest(requestUrl,
749                 browserVersion.getHtmlAcceptHeader(), browserVersion.getAcceptEncodingHeader());
750 
751         webRequest.markAsNavigation(getUrl(), false);
752         webRequest.setFetchModeOverride(WebRequest.FetchMode.NAVIGATE);
753 
754         webRequest.setRefererHeader(getUrl());
755         if (webWindow.getEnclosedPage() instanceof HtmlPage referrerPage) {
756             webRequest.setReferrerPolicy(referrerPage.getReferrerPolicy());
757         }
758 
759         if (webWindow.getEnclosedPage() instanceof HtmlPage page) {
760             upgradeInsecureRedirects(page, webWindow, webRequest);
761         }
762 
763         webClient.getPage(webWindow, webRequest);
764     }
765 
766     /**
767      * Returns the {@code origin} property.
768      *
769      * @return the {@code origin} property
770      */
771     public String getOrigin() {
772         return getUrl().getProtocol() + "://" + getHost();
773     }
774 }