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;
16  
17  import java.io.IOException;
18  import java.io.ObjectInputStream;
19  import java.io.Serializable;
20  import java.lang.ref.SoftReference;
21  import java.net.URL;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import org.htmlunit.javascript.host.Window;
26  import org.htmlunit.javascript.host.event.Event;
27  import org.htmlunit.javascript.host.event.PopStateEvent;
28  import org.htmlunit.util.HeaderUtils;
29  import org.htmlunit.util.UrlUtils;
30  
31  /**
32   * Representation of the navigation history of a single window.
33   *
34   * @author Daniel Gredler
35   * @author Ahmed Ashour
36   * @author Adam Afeltowicz
37   * @author Ronald Brill
38   * @author Madis Pärn
39   * @author Vidya m
40   */
41  public class History implements Serializable {
42  
43      /** The window to which this navigation history belongs. */
44      private final WebWindow window_;
45  
46      /**
47       * Whether or not to ignore calls to {@link #addPage(Page)}; this is a bit hackish (we should probably be using
48       * explicit boolean parameters in the various methods that load new pages), but it does the job for now -- without
49       * any new API cruft.
50       */
51      private transient ThreadLocal<Boolean> ignoreNewPages_;
52  
53      /**
54       * The {@link History.HistoryEntry}s in this navigation history.
55       */
56      private final List<HistoryEntry> entries_ = new ArrayList<>();
57  
58      /** The current index within the list of pages which make up this navigation history. */
59      private int index_ = -1;
60  
61      /**
62       * The single entry in the history.
63       */
64      private static final class HistoryEntry implements Serializable {
65          private transient SoftReference<Page> page_;
66          private final WebRequest webRequest_;
67          private Object state_;
68  
69          HistoryEntry(final Page page) {
70  
71              // verify cache-control header values before storing
72              if (HeaderUtils.containsNoStore(page.getWebResponse())) {
73                  page_ = null;
74              }
75              else {
76                  page_ = new SoftReference<>(page);
77              }
78  
79              final WebRequest request = page.getWebResponse().getWebRequest();
80              webRequest_ = new WebRequest(request.getUrl(), request.getHttpMethod());
81              webRequest_.setRequestParameters(request.getRequestParameters());
82          }
83  
84          Page getPage() {
85              if (page_ == null) {
86                  return null;
87              }
88              return page_.get();
89          }
90  
91          void clearPage() {
92              page_ = null;
93          }
94  
95          WebRequest getWebRequest() {
96              return webRequest_;
97          }
98  
99          URL getUrl() {
100             return webRequest_.getUrl();
101         }
102 
103         void setUrl(final URL url, final Page page) {
104             if (url != null) {
105                 WebWindow webWindow = null;
106                 if (page != null) {
107                     webWindow = page.getEnclosingWindow();
108                 }
109 
110                 final URL encoded = UrlUtils.encodeUrl(url, webRequest_.getCharset());
111                 webRequest_.setUrl(encoded);
112                 if (page != null) {
113                     page.getWebResponse().getWebRequest().setUrl(encoded);
114                     if (webWindow != null) {
115                         final Window win = webWindow.getScriptableObject();
116                         if (win != null) {
117                             win.getLocation().setHash(null, encoded.getRef(), false);
118                         }
119                     }
120                 }
121             }
122         }
123 
124         /**
125          * Returns the state object.
126          *
127          * @return the state object
128          */
129         Object getState() {
130             return state_;
131         }
132 
133         /**
134          * Sets the state object.
135          * @param state the state object to use
136          */
137         void setState(final Object state) {
138             state_ = state;
139         }
140     }
141 
142     /**
143      * Creates a new navigation history for the specified window.
144      * @param window the window which owns the new navigation history
145      */
146     public History(final WebWindow window) {
147         window_ = window;
148         initTransientFields();
149     }
150 
151     /**
152      * Initializes the transient fields.
153      */
154     private void initTransientFields() {
155         ignoreNewPages_ = new ThreadLocal<>();
156     }
157 
158     /**
159      * Returns the length of the navigation history.
160      * @return the length of the navigation history
161      */
162     public int getLength() {
163         return entries_.size();
164     }
165 
166     /**
167      * Returns the current (zero-based) index within the navigation history.
168      * @return the current (zero-based) index within the navigation history
169      */
170     public int getIndex() {
171         return index_;
172     }
173 
174     /**
175      * Returns the URL at the specified index in the navigation history, or {@code null} if the index is not valid.
176      * @param index the index of the URL to be returned
177      * @return the URL at the specified index in the navigation history, or {@code null} if the index is not valid
178      */
179     public URL getUrl(final int index) {
180         if (index >= 0 && index < entries_.size()) {
181             return UrlUtils.toUrlSafe(entries_.get(index).getUrl().toExternalForm());
182         }
183         return null;
184     }
185 
186     /**
187      * Goes back one step in the navigation history, if possible.
188      * @return this navigation history, after going back one step
189      * @throws IOException in case of error
190      */
191     public History back() throws IOException {
192         if (index_ > 0) {
193             index_--;
194             goToUrlAtCurrentIndex();
195         }
196         return this;
197     }
198 
199     /**
200      * Goes forward one step in the navigation history, if possible.
201      * @return this navigation history, after going forward one step
202      * @throws IOException in case of error
203      */
204     public History forward() throws IOException {
205         if (index_ < entries_.size() - 1) {
206             index_++;
207             goToUrlAtCurrentIndex();
208         }
209         return this;
210     }
211 
212     /**
213      * Goes forward or backwards in the navigation history, according to whether the specified relative index
214      * is positive or negative. If the specified index is <code>0</code>, this method reloads the current page.
215      * @param relativeIndex the index to move to, relative to the current index
216      * @return this navigation history, after going forwards or backwards the specified number of steps
217      * @throws IOException in case of error
218      */
219     public History go(final int relativeIndex) throws IOException {
220         final int i = index_ + relativeIndex;
221         if (i < entries_.size() && i >= 0) {
222             index_ = i;
223             goToUrlAtCurrentIndex();
224         }
225         return this;
226     }
227 
228     /**
229      * {@inheritDoc}
230      */
231     @Override
232     public String toString() {
233         return entries_.toString();
234     }
235 
236     /**
237      * Removes the current URL from the history.
238      */
239     public void removeCurrent() {
240         if (index_ >= 0 && index_ < entries_.size()) {
241             entries_.remove(index_);
242             if (index_ > 0) {
243                 index_--;
244             }
245         }
246     }
247 
248     /**
249      * Adds a new page to the navigation history.
250      * @param page the page to add to the navigation history
251      * @return the created history entry
252      */
253     protected HistoryEntry addPage(final Page page) {
254         final Boolean ignoreNewPages = ignoreNewPages_.get();
255         if (ignoreNewPages != null && ignoreNewPages.booleanValue()) {
256             return null;
257         }
258 
259         final int sizeLimit = window_.getWebClient().getOptions().getHistorySizeLimit();
260         if (sizeLimit <= 0) {
261             entries_.clear();
262             index_ = -1;
263             return null;
264         }
265 
266         index_++;
267         while (entries_.size() > index_) {
268             entries_.remove(index_);
269         }
270         while (entries_.size() >= sizeLimit) {
271             entries_.remove(0);
272             index_--;
273         }
274 
275         final HistoryEntry entry = new HistoryEntry(page);
276         entries_.add(entry);
277 
278         final int cacheLimit = Math.max(window_.getWebClient().getOptions().getHistoryPageCacheLimit(), 0);
279         if (entries_.size() > cacheLimit) {
280             entries_.get(entries_.size() - cacheLimit - 1).clearPage();
281         }
282 
283         return entry;
284     }
285 
286     /**
287      * Loads the URL at the current index into the window to which this navigation history belongs.
288      * @throws IOException if an IO error occurs
289      */
290     private void goToUrlAtCurrentIndex() throws IOException {
291         final Boolean old = ignoreNewPages_.get();
292         ignoreNewPages_.set(Boolean.TRUE);
293         try {
294 
295             final HistoryEntry entry = entries_.get(index_);
296 
297             final Page page = entry.getPage();
298             if (page == null) {
299                 window_.getWebClient().getPage(window_, entry.getWebRequest(), false);
300             }
301             else {
302                 window_.setEnclosedPage(page);
303                 page.getWebResponse().getWebRequest().setUrl(entry.getUrl());
304             }
305 
306             final Window jsWindow = window_.getScriptableObject();
307             if (jsWindow != null && jsWindow.hasEventHandlers("onpopstate")) {
308                 final Event event = new PopStateEvent(jsWindow, Event.TYPE_POPSTATE, entry.getState());
309                 jsWindow.executeEventLocally(event);
310             }
311         }
312         finally {
313             ignoreNewPages_.set(old);
314         }
315     }
316 
317     /**
318      * Allows to change history state and url if provided.
319      *
320      * @param state the new state to use
321      * @param url the new url to use
322      */
323     public void replaceState(final Object state, final URL url) {
324         if (index_ >= 0 && index_ < entries_.size()) {
325             final HistoryEntry entry = entries_.get(index_);
326 
327             Page page = entry.getPage();
328             if (page == null) {
329                 page = window_.getEnclosedPage();
330             }
331 
332             entry.setUrl(url, page);
333             entry.setState(state);
334         }
335     }
336 
337     /**
338      * Allows to change history state and url if provided.
339      *
340      * @param state the new state to use
341      * @param url the new url to use
342      */
343     public void pushState(final Object state, final URL url) {
344         final Page page = window_.getEnclosedPage();
345         final HistoryEntry entry = addPage(page);
346 
347         if (entry != null) {
348             entry.setUrl(url, page);
349             entry.setState(state);
350         }
351     }
352 
353     /**
354      * Returns current state object.
355      *
356      * @return the current state object
357      */
358     public Object getCurrentState() {
359         if (index_ >= 0 && index_ < entries_.size()) {
360             return entries_.get(index_).getState();
361         }
362         return null;
363     }
364 
365     /**
366      * Re-initializes transient fields when an object of this type is deserialized.
367      * @param in the object input stream
368      * @throws IOException if an error occurs
369      * @throws ClassNotFoundException if an error occurs
370      */
371     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
372         in.defaultReadObject();
373         initTransientFields();
374     }
375 }