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.net.URL;
21  import java.util.HashMap;
22  import java.util.LinkedHashMap;
23  import java.util.Locale;
24  import java.util.Map;
25  import java.util.WeakHashMap;
26  
27  import org.htmlunit.html.HtmlPage;
28  import org.htmlunit.util.UrlUtils;
29  
30  /**
31   * Holder for different types of storages.
32   * <p><span style="color:red">Experimental API: May be changed in next release!</span></p>
33   *
34   * @author Ahmed Ashour
35   * @author Ronald Brill
36   * @author Marc Guillemot
37   * @author Vidya m
38   */
39  public class StorageHolder implements Serializable {
40  
41      /**
42       * Type for Storage.
43       */
44      public enum Type {
45          /** The type for window.localStorage. */
46          LOCAL_STORAGE,
47          /** The type for window.sessionStorage. */
48          SESSION_STORAGE
49      }
50  
51      /** Key of the session storage not (yet) bound to an origin. */
52      private static final String UNBOUND_KEY = "";
53  
54      private final Map<String, Map<String, String>> localStorage_ = new HashMap<>();
55      private transient Map<WebWindow, Map<String, Map<String, String>>> sessionStorage_ = new WeakHashMap<>();
56  
57      /**
58       * Gets the store of the give type for the page.
59       * The local storage is shared by all pages of the same origin; the session storage
60       * is shared by all pages of the same origin inside the same top level window.
61       * Pages without an origin of their own (e.g. about:blank iframes) are using
62       * the origin of their creator.
63       *
64       * @param storageType the type
65       * @param page the page
66       * @return the store
67       */
68      public Map<String, String> getStore(final Type storageType, final Page page) {
69          final URL originUrl = getOriginUrl(page);
70          return switch (storageType) {
71              case LOCAL_STORAGE -> getLocalStorage(originUrl);
72              case SESSION_STORAGE -> getSessionStorage(page.getEnclosingWindow(), originUrl);
73          };
74      }
75  
76      /**
77       * Gets the local storage (map).
78       * @param url the page origin
79       * @return the store
80       */
81      public Map<String, String> getLocalStorage(final URL url) {
82          synchronized (localStorage_) {
83              return localStorage_.computeIfAbsent(getOriginKey(url), k -> new LinkedHashMap<>());
84          }
85      }
86  
87      /**
88       * Gets the session storage (map) of the window for the origin of the page
89       * currently loaded into the window.
90       *
91       * <p>If the window has no page with an origin yet (no page or about:blank), a store
92       * not bound to an origin is returned; this store is used as session storage
93       * for the origin of the first page loaded into this window that accesses the
94       * session storage. This allows to pre-populate the session storage before loading
95       * the page; {@link #getSessionStorage(WebWindow, URL)} is the preferred way to do this.</p>
96       *
97       * @param webWindow the window
98       * @return the store
99       */
100     public Map<String, String> getSessionStorage(final WebWindow webWindow) {
101         final Page page = webWindow.getEnclosedPage();
102         if (page == null || page.getUrl() == null) {
103             return getUnboundSessionStorage(webWindow);
104         }
105 
106         final URL originUrl = getOriginUrl(page);
107         if (UrlUtils.ABOUT.equals(originUrl.getProtocol())) {
108             return getUnboundSessionStorage(webWindow);
109         }
110         return getSessionStorage(webWindow, originUrl);
111     }
112 
113     /**
114      * Gets the session storage (map) of the window for the given origin.
115      * The session storage is shared by all windows (including frames) of the
116      * same top level window.
117      * @param webWindow the window
118      * @param url the origin
119      * @return the store
120      */
121     public Map<String, String> getSessionStorage(final WebWindow webWindow, final URL url) {
122         synchronized (sessionStorage_) {
123             final Map<String, Map<String, String>> stores =
124                     sessionStorage_.computeIfAbsent(webWindow.getTopWindow(), k -> new HashMap<>());
125             final String key = getOriginKey(url);
126             Map<String, String> store = stores.get(key);
127             if (store == null) {
128                 // adopt the store pre-populated via getSessionStorage(WebWindow) if there is one
129                 if (!UrlUtils.ABOUT.equals(url.getProtocol())) {
130                     store = stores.remove(UNBOUND_KEY);
131                 }
132                 if (store == null) {
133                     store = new LinkedHashMap<>();
134                 }
135                 stores.put(key, store);
136             }
137             return store;
138         }
139     }
140 
141     private Map<String, String> getUnboundSessionStorage(final WebWindow webWindow) {
142         synchronized (sessionStorage_) {
143             return sessionStorage_
144                     .computeIfAbsent(webWindow.getTopWindow(), k -> new HashMap<>())
145                     .computeIfAbsent(UNBOUND_KEY, k -> new LinkedHashMap<>());
146         }
147     }
148 
149     /**
150      * Copies the session storage of the opener's origin into the session storage
151      * of a newly opened top level window (e.g. by window.open()).
152      * Nothing is copied if the target window already has session storage for this origin.
153      * @param opener the window that opened the new one
154      * @param newWindow the new window
155      */
156     public void copySessionStorage(final WebWindow opener, final WebWindow newWindow) {
157         final Page openerPage = opener.getEnclosedPage();
158         if (openerPage == null || openerPage.getUrl() == null) {
159             return;
160         }
161         final String key = getOriginKey(getOriginUrl(openerPage));
162 
163         synchronized (sessionStorage_) {
164             final WebWindow openerTop = opener.getTopWindow();
165             final WebWindow newTop = newWindow.getTopWindow();
166             if (openerTop == newTop) {
167                 return;
168             }
169 
170             final Map<String, Map<String, String>> openerStores = sessionStorage_.get(openerTop);
171             if (openerStores == null) {
172                 return;
173             }
174             final Map<String, String> openerStore = openerStores.get(key);
175             if (openerStore == null || openerStore.isEmpty()) {
176                 return;
177             }
178 
179             final Map<String, Map<String, String>> newStores =
180                     sessionStorage_.computeIfAbsent(newTop, k -> new HashMap<>());
181             if (!newStores.containsKey(key)) {
182                 synchronized (openerStore) {
183                     newStores.put(key, new LinkedHashMap<>(openerStore));
184                 }
185             }
186         }
187     }
188 
189     private static URL getOriginUrl(final Page page) {
190         if (page instanceof HtmlPage htmlPage) {
191             return htmlPage.getOriginUrl();
192         }
193         return page.getUrl();
194     }
195 
196     private static String getOriginKey(final URL url) {
197         // the storage is per origin (scheme, host and port)
198         int port = url.getPort();
199         if (port == -1) {
200             port = url.getDefaultPort();
201         }
202         return url.getProtocol() + "://" + url.getHost().toLowerCase(Locale.ROOT) + ":" + port;
203     }
204 
205     private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
206         ois.defaultReadObject();
207 
208         sessionStorage_ = new WeakHashMap<>();
209     }
210 }