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_STORAGE_PRESERVED_INCLUDED;
18  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.HashSet;
22  import java.util.List;
23  import java.util.Map;
24  
25  import org.htmlunit.Page;
26  import org.htmlunit.StorageHolder;
27  import org.htmlunit.StorageHolder.Type;
28  import org.htmlunit.WebClient;
29  import org.htmlunit.WebWindow;
30  import org.htmlunit.corejs.javascript.CompoundOperationMap;
31  import org.htmlunit.corejs.javascript.Context;
32  import org.htmlunit.corejs.javascript.Function;
33  import org.htmlunit.corejs.javascript.Scriptable;
34  import org.htmlunit.corejs.javascript.ScriptableObject;
35  import org.htmlunit.corejs.javascript.VarScope;
36  import org.htmlunit.html.HtmlPage;
37  import org.htmlunit.javascript.AbstractJavaScriptEngine;
38  import org.htmlunit.javascript.HtmlUnitContextFactory;
39  import org.htmlunit.javascript.HtmlUnitScriptable;
40  import org.htmlunit.javascript.JavaScriptEngine;
41  import org.htmlunit.javascript.PostponedAction;
42  import org.htmlunit.javascript.configuration.JsxClass;
43  import org.htmlunit.javascript.configuration.JsxConstructor;
44  import org.htmlunit.javascript.configuration.JsxFunction;
45  import org.htmlunit.javascript.configuration.JsxGetter;
46  import org.htmlunit.javascript.host.dom.DOMException;
47  import org.htmlunit.javascript.host.event.Event;
48  import org.htmlunit.javascript.host.event.StorageEvent;
49  
50  /**
51   * JavaScript host object for {@code Storage}.
52   *
53   * @author Ahmed Ashour
54   * @author Marc Guillemot
55   * @author Ronald Brill
56   * @author Kanoko Yamamoto
57   *
58   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN Documentation</a>
59   * @see <a href="https://html.spec.whatwg.org/multipage/webstorage.html">HTML Living Standard - Web storage</a>
60   */
61  @JsxClass
62  public class Storage extends HtmlUnitScriptable {
63  
64      private static final HashSet<String> RESERVED_NAMES_ = new HashSet<>(Arrays.asList(
65          "clear", "key", "getItem", "length", "removeItem",
66          "setItem", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "propertyIsEnumerable",
67          "isPrototypeOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"));
68  
69      /** The quota (5 MiB) in characters; keys and values are counted. */
70      private static final long STORE_SIZE_LIMIT = 5L * 1024 * 1024;
71  
72      private final Map<String, String> store_;
73      private final Type type_;
74  
75      /**
76       * Default constructor for prototype instantiation only.
77       */
78      public Storage() {
79          super();
80          store_ = null;
81          type_ = null;
82      }
83  
84      /**
85       * Creates an instance of this object.
86       */
87      @JsxConstructor
88      public void jsConstructor() {
89          // nothing to do
90      }
91  
92      /**
93       * Creates a new {@code Storage} instance backed by the given store.
94       * No storage events are fired for changes made through this instance.
95       *
96       * @param window the parent scope
97       * @param store the backing map for this storage
98       */
99      public Storage(final Window window, final Map<String, String> store) {
100         this(window, store, null);
101     }
102 
103     /**
104      * Creates a new {@code Storage} instance backed by the given store.
105      *
106      * @param window the parent scope
107      * @param store the backing map for this storage
108      * @param type the type of this storage, used to fire storage events in other windows;
109      *        if {@code null} no events are fired
110      */
111     public Storage(final Window window, final Map<String, String> store, final Type type) {
112         super();
113         store_ = store;
114         type_ = type;
115         setParentScope(getTopLevelScope(window.getParentScope()));
116         setPrototype(window.getPrototype(Storage.class));
117     }
118 
119     /**
120      * {@inheritDoc}
121      */
122     @Override
123     public void put(final String name, final Scriptable start, final Object value) {
124         final boolean isReserved = RESERVED_NAMES_.contains(name);
125         if (store_ == null || isReserved) {
126             super.put(name, start, value);
127         }
128         if (store_ != null && (!isReserved || getBrowserVersion().hasFeature(JS_STORAGE_PRESERVED_INCLUDED))) {
129             setItem(name, JavaScriptEngine.toString(value));
130         }
131     }
132 
133     /**
134      * {@inheritDoc}
135      */
136     @Override
137     public Object get(final String name, final Scriptable start) {
138         if (store_ == null || RESERVED_NAMES_.contains(name)) {
139             return super.get(name, start);
140         }
141         final Object value = getItem(name);
142         if (value != null) {
143             return value;
144         }
145         return super.get(name, start);
146     }
147 
148     /**
149      * Overridden to make the stored items visible as own properties.
150      * {@inheritDoc}
151      */
152     @Override
153     public boolean has(final String name, final Scriptable start) {
154         return isItem(name) || super.has(name, start);
155     }
156 
157     /**
158      * Overridden to support the removal of stored items via {@code delete}.
159      * {@inheritDoc}
160      */
161     @Override
162     public void delete(final String name) {
163         if (isItem(name) && !super.has(name, this)) {
164             removeItem(name);
165             return;
166         }
167         super.delete(name);
168     }
169 
170     /**
171      * Overridden to enumerate the stored items as own properties
172      * (Object.keys(), Object.getOwnPropertyNames(), for...in, ...).
173      * {@inheritDoc}
174      */
175     @Override
176     protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
177             final boolean getNonEnumerable, final boolean getSymbols) {
178         return addItemIds(super.getIds(map, getNonEnumerable, getSymbols));
179     }
180 
181     /**
182      * Overridden to provide property descriptors for the stored items.
183      * {@inheritDoc}
184      */
185     @Override
186     protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
187         final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
188         if (descInfo != null) {
189             return descInfo;
190         }
191 
192         if (id instanceof CharSequence) {
193             final String name = id.toString();
194             if (isItem(name)) {
195                 final Object value = getItem(name);
196                 if (value != null) {
197                     return ScriptableObject.buildDataDescriptor(value, ScriptableObject.EMPTY);
198                 }
199             }
200         }
201         return null;
202     }
203 
204     private boolean isItem(final String name) {
205         if (store_ == null || RESERVED_NAMES_.contains(name)) {
206             return false;
207         }
208         synchronized (store_) {
209             return store_.containsKey(name);
210         }
211     }
212 
213     private Object[] addItemIds(final Object[] ids) {
214         if (store_ == null) {
215             return ids;
216         }
217 
218         final List<Object> result = new ArrayList<>();
219         synchronized (store_) {
220             for (final String key : store_.keySet()) {
221                 if (!RESERVED_NAMES_.contains(key)) {
222                     result.add(key);
223                 }
224             }
225         }
226         for (final Object id : ids) {
227             if (!result.contains(id)) {
228                 result.add(id);
229             }
230         }
231         return result.toArray();
232     }
233 
234     /**
235      * Returns the number of items in the storage.
236      *
237      * @return the number of items
238      */
239     @JsxGetter
240     public int getLength() {
241         synchronized (store_) {
242             return store_.size();
243         }
244     }
245 
246     /**
247      * Removes the item with the specified key.
248      *
249      * @param key the key of the item to remove
250      */
251     public void removeItem(final String key) {
252         final String removed;
253         synchronized (store_) {
254             removed = store_.remove(key);
255         }
256         if (removed != null) {
257             fireStorageEvent(key, removed, null);
258         }
259     }
260 
261     /**
262      * Implementation of the JavaScript function {@code removeItem(key)}.
263      *
264      * @param context the context
265      * @param scope the scope
266      * @param thisObj this object
267      * @param args the arguments
268      * @param function the function
269      */
270     @JsxFunction(functionName = "removeItem")
271     public static void jsRemoveItem(final Context context, final VarScope scope,
272             final Scriptable thisObj, final Object[] args, final Function function) {
273         checkArguments(args, 1, "removeItem");
274         getStorage(thisObj).removeItem(JavaScriptEngine.toString(args[0]));
275     }
276 
277     /**
278      * Returns the key at the specified index.
279      *
280      * @param index the index of the key to retrieve
281      * @return the key at the given index, or {@code null} if out of range
282      */
283     public String key(final int index) {
284         if (index >= 0) {
285             synchronized (store_) {
286                 int counter = 0;
287                 for (final String key : store_.keySet()) {
288                     if (counter == index) {
289                         return key;
290                     }
291                     counter++;
292                 }
293             }
294         }
295         return null;
296     }
297 
298     /**
299      * Implementation of the JavaScript function {@code key(index)}.
300      *
301      * @param context the context
302      * @param scope the scope
303      * @param thisObj this object
304      * @param args the arguments
305      * @param function the function
306      * @return the key at the given index, or {@code null} if out of range
307      */
308     @JsxFunction(functionName = "key")
309     public static String jsKey(final Context context, final VarScope scope,
310             final Scriptable thisObj, final Object[] args, final Function function) {
311         checkArguments(args, 1, "key");
312         final Storage storage = getStorage(thisObj);
313         final long index = JavaScriptEngine.toUint32(args[0]);
314         if (index > Integer.MAX_VALUE) {
315             return null;
316         }
317         return storage.key((int) index);
318     }
319 
320     /**
321      * Returns the value associated with the given key.
322      *
323      * @param key the key of the item to retrieve
324      * @return the value for the given key, or {@code null} if not found
325      */
326     public Object getItem(final String key) {
327         synchronized (store_) {
328             return store_.get(key);
329         }
330     }
331 
332     /**
333      * Implementation of the JavaScript function {@code getItem(key)}.
334      *
335      * @param context the context
336      * @param scope the scope
337      * @param thisObj this object
338      * @param args the arguments
339      * @param function the function
340      * @return the value for the given key, or {@code null} if not found
341      */
342     @JsxFunction(functionName = "getItem")
343     public static Object jsGetItem(final Context context, final VarScope scope,
344             final Scriptable thisObj, final Object[] args, final Function function) {
345         checkArguments(args, 1, "getItem");
346         return getStorage(thisObj).getItem(JavaScriptEngine.toString(args[0]));
347     }
348 
349     /**
350      * Sets the value for the given key.
351      * The quota is shared by all {@code Storage} objects using the same store
352      * and counts the length of the keys and of the values.
353      *
354      * @param key the key of the item to set
355      * @param data the new value
356      */
357     public void setItem(final String key, final String data) {
358         final String oldData;
359         synchronized (store_) {
360             oldData = store_.get(key);
361             if (data.equals(oldData)) {
362                 return;
363             }
364 
365             long storeSize = key.length() + data.length();
366             for (final Map.Entry<String, String> entry : store_.entrySet()) {
367                 if (!key.equals(entry.getKey())) {
368                     storeSize += entry.getKey().length() + entry.getValue().length();
369                 }
370             }
371             if (storeSize > STORE_SIZE_LIMIT) {
372                 throw JavaScriptEngine.asJavaScriptException(this,
373                         "Failed to execute 'setItem' on 'Storage': "
374                                 + "Setting the value of '" + key + "' exceeded the quota.",
375                         DOMException.QUOTA_EXCEEDED_ERR);
376             }
377             store_.put(key, data);
378         }
379         fireStorageEvent(key, oldData, data);
380     }
381 
382     /**
383      * Implementation of the JavaScript function {@code setItem(key, value)}.
384      *
385      * @param context the context
386      * @param scope the scope
387      * @param thisObj this object
388      * @param args the arguments
389      * @param function the function
390      */
391     @JsxFunction(functionName = "setItem")
392     public static void jsSetItem(final Context context, final VarScope scope,
393             final Scriptable thisObj, final Object[] args, final Function function) {
394         checkArguments(args, 2, "setItem");
395         getStorage(thisObj).setItem(JavaScriptEngine.toString(args[0]), JavaScriptEngine.toString(args[1]));
396     }
397 
398     /**
399      * Removes all items from this storage.
400      */
401     @JsxFunction
402     public void clear() {
403         synchronized (store_) {
404             if (store_.isEmpty()) {
405                 return;
406             }
407             store_.clear();
408         }
409         fireStorageEvent(null, null, null);
410     }
411 
412     private static Storage getStorage(final Scriptable thisObj) {
413         if (thisObj instanceof Storage storage && storage.store_ != null) {
414             return storage;
415         }
416         throw JavaScriptEngine.typeError("Illegal invocation");
417     }
418 
419     private static void checkArguments(final Object[] args, final int required, final String functionName) {
420         if (args.length < required) {
421             throw JavaScriptEngine.typeError("Failed to execute '" + functionName + "' on 'Storage': "
422                     + required + " argument" + (required > 1 ? "s" : "") + " required, but only "
423                     + args.length + " present.");
424         }
425     }
426 
427     /**
428      * Queues a {@code storage} event for every other window (including frames)
429      * sharing the same storage area.
430      *
431      * @param key the changed key or {@code null} for clear()
432      * @param oldValue the old value or {@code null}
433      * @param newValue the new value or {@code null}
434      */
435     private void fireStorageEvent(final String key, final String oldValue, final String newValue) {
436         if (type_ == null) {
437             return;
438         }
439 
440         final Window window = getWindow();
441         final WebWindow sourceWindow = window.getWebWindow();
442         final Page sourcePage = sourceWindow.getEnclosedPage();
443         if (sourcePage == null || sourcePage.getUrl() == null) {
444             return;
445         }
446         final String url = sourcePage.getUrl().toExternalForm();
447 
448         final WebClient webClient = sourceWindow.getWebClient();
449         final StorageHolder storageHolder = webClient.getStorageHolder();
450         final AbstractJavaScriptEngine<?> jsEngine = webClient.getJavaScriptEngine();
451 
452         for (final WebWindow webWindow : webClient.getWebWindows()) {
453             if (webWindow == sourceWindow) {
454                 continue;
455             }
456             if (type_ == Type.SESSION_STORAGE && webWindow.getTopWindow() != sourceWindow.getTopWindow()) {
457                 continue;
458             }
459             if (!(webWindow.getEnclosedPage() instanceof HtmlPage page)) {
460                 continue;
461             }
462             if (storageHolder.getStore(type_, page) != store_) {
463                 continue;
464             }
465             final Window receiver = webWindow.getScriptableObject();
466             if (receiver == null) {
467                 continue;
468             }
469 
470             final PostponedAction action = new PostponedAction(page, "Storage event") {
471                 @Override
472                 public void execute() {
473                     final StorageEvent event = new StorageEvent();
474                     event.setParentScope(getTopLevelScope(receiver.getParentScope()));
475                     event.setPrototype(receiver.getPrototype(StorageEvent.class));
476                     event.initStorageEvent(Event.TYPE_STORAGE, false, false,
477                             key, oldValue, newValue, url, receiver.getStorage(type_));
478 
479                     final HtmlUnitContextFactory cf = jsEngine.getContextFactory();
480                     cf.call(cx -> receiver.dispatchEvent(event));
481                 }
482             };
483             jsEngine.addPostponedAction(action);
484         }
485     }
486 }