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 java.io.IOException;
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  
21  import org.htmlunit.WebWindow;
22  import org.htmlunit.html.HtmlPage;
23  import org.htmlunit.javascript.HtmlUnitScriptable;
24  import org.htmlunit.javascript.JavaScriptEngine;
25  import org.htmlunit.javascript.configuration.JsxClass;
26  import org.htmlunit.javascript.configuration.JsxConstructor;
27  import org.htmlunit.javascript.configuration.JsxFunction;
28  import org.htmlunit.javascript.configuration.JsxGetter;
29  import org.htmlunit.javascript.configuration.JsxSetter;
30  import org.htmlunit.javascript.host.dom.DOMException;
31  import org.htmlunit.util.StringUtils;
32  import org.htmlunit.util.UrlUtils;
33  
34  /**
35   * JavaScript host object for the client's browsing history.
36   *
37   * @author Mike Bowler
38   * @author Chris Erskine
39   * @author Daniel Gredler
40   * @author Ahmed Ashour
41   * @author Ronald Brill
42   * @author Adam Afeltowicz
43   * @author Lai Quang Duong
44   *
45   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/History">MDN Documentation</a>
46   */
47  @JsxClass
48  public class History extends HtmlUnitScriptable {
49      private static final String SCROLL_RESTAURATION_AUTO = "auto";
50      private static final String SCROLL_RESTAURATION_MANUAL = "manual";
51  
52      private String scrollRestoration_ = SCROLL_RESTAURATION_AUTO;
53  
54      /**
55       * Creates an instance of this object.
56       */
57      @JsxConstructor
58      public void jsConstructor() {
59          // nothing to do
60      }
61  
62      /**
63       * Returns the {@code length} property.
64       *
65       * @return the number of entries in the session history
66       */
67      @JsxGetter
68      public int getLength() {
69          final WebWindow w = getWindow().getWebWindow();
70          return w.getHistory().getLength();
71      }
72  
73      /**
74       * Returns the {@code state} property.
75       *
76       * @return the current history state object
77       */
78      @JsxGetter
79      public Object getState() {
80          final WebWindow w = getWindow().getWebWindow();
81          return w.getHistory().getCurrentState();
82      }
83  
84      /**
85       * Navigates one step back in the session history.
86       */
87      @JsxFunction
88      public void back() {
89          try {
90              getWindow().getWebWindow().getHistory().back();
91          }
92          catch (final IOException e) {
93              throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
94          }
95      }
96  
97      /**
98       * Navigates one step forward in the session history.
99       */
100     @JsxFunction
101     public void forward() {
102         try {
103             getWindow().getWebWindow().getHistory().forward();
104         }
105         catch (final IOException e) {
106             throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
107         }
108     }
109 
110     /**
111      * Navigates by the given number of steps relative to the current position in the session history.
112      *
113      * @param relativeIndex the relative number of steps to navigate (positive or negative)
114      */
115     @JsxFunction
116     public void go(final int relativeIndex) {
117         try {
118             getWindow().getWebWindow().getHistory().go(relativeIndex);
119         }
120         catch (final IOException e) {
121             throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
122         }
123     }
124 
125     /**
126      * Replaces the current history entry with the given state.
127      *
128      * @param object the new state object
129      * @param title the title (currently ignored by most browsers)
130      * @param url an optional new URL for the history entry
131      */
132     @JsxFunction
133     public void replaceState(final Object object, final String title, final Object url) {
134         final WebWindow w = getWindow().getWebWindow();
135         try {
136             w.getHistory().replaceState(object, buildNewStateUrl(w, url));
137         }
138         catch (final MalformedURLException e) {
139             throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
140         }
141     }
142 
143     /**
144      * Pushes a new state onto the session history stack.
145      *
146      * @param object the new state object
147      * @param title the title (currently ignored by most browsers)
148      * @param url an optional new URL for the new history entry
149      */
150     @JsxFunction
151     public void pushState(final Object object, final String title, final Object url) {
152         final WebWindow w = getWindow().getWebWindow();
153         try {
154             w.getHistory().pushState(object, buildNewStateUrl(w, url));
155         }
156         catch (final IOException e) {
157             throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
158         }
159     }
160 
161     private URL buildNewStateUrl(final WebWindow webWindow, final Object url) throws MalformedURLException {
162         URL newStateUrl = null;
163         if (url != null && !JavaScriptEngine.isUndefined(url)) {
164             final String urlString = JavaScriptEngine.toString(url);
165             if (StringUtils.isNotBlank(urlString)) {
166                 final HtmlPage page = (HtmlPage) webWindow.getEnclosedPage();
167                 newStateUrl = page.getFullyQualifiedUrl(urlString);
168 
169                 // the document url can only be changed inside the origin of the document
170                 // https://html.spec.whatwg.org/multipage/nav-history-apis.html#can-have-its-url-rewritten
171                 if (!UrlUtils.isSameOrigin(page.getUrl(), newStateUrl)) {
172                     throw JavaScriptEngine.asJavaScriptException(
173                             getWindow(),
174                             "A history state object with URL '" + newStateUrl.toExternalForm()
175                                 + "' cannot be created in a document with URL '"
176                                 + page.getUrl().toExternalForm() + "'.",
177                             DOMException.SECURITY_ERR);
178                 }
179             }
180         }
181         return newStateUrl;
182     }
183 
184     /**
185      * Returns the {@code scrollRestoration} property.
186      *
187      * @return the {@code scrollRestoration} property
188      */
189     @JsxGetter
190     public String getScrollRestoration() {
191         return scrollRestoration_;
192     }
193 
194     /**
195      * Sets the {@code scrollRestoration} property.
196      *
197      * @param scrollRestoration the new value; either {@code "auto"} or {@code "manual"}
198      */
199     @JsxSetter
200     public void setScrollRestoration(final String scrollRestoration) {
201         if (SCROLL_RESTAURATION_AUTO.equals(scrollRestoration)) {
202             scrollRestoration_ = SCROLL_RESTAURATION_AUTO;
203             return;
204         }
205         if (SCROLL_RESTAURATION_MANUAL.equals(scrollRestoration)) {
206             scrollRestoration_ = SCROLL_RESTAURATION_MANUAL;
207         }
208     }
209 }