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.dom;
16  
17  import java.util.ArrayList;
18  import java.util.List;
19  import java.util.Set;
20  
21  import org.apache.commons.lang3.StringUtils;
22  import org.htmlunit.WebClient;
23  import org.htmlunit.corejs.javascript.Context;
24  import org.htmlunit.corejs.javascript.ContextAction;
25  import org.htmlunit.corejs.javascript.Function;
26  import org.htmlunit.corejs.javascript.Scriptable;
27  import org.htmlunit.corejs.javascript.VarScope;
28  import org.htmlunit.html.BaseFrameElement;
29  import org.htmlunit.html.DomAttr;
30  import org.htmlunit.html.DomElement;
31  import org.htmlunit.html.DomNode;
32  import org.htmlunit.javascript.HtmlUnitContextFactory;
33  import org.htmlunit.javascript.HtmlUnitScriptable;
34  import org.htmlunit.javascript.JavaScriptEngine;
35  import org.htmlunit.javascript.configuration.JsxClass;
36  import org.htmlunit.javascript.configuration.JsxConstructor;
37  import org.htmlunit.javascript.configuration.JsxFunction;
38  import org.htmlunit.javascript.configuration.JsxGetter;
39  import org.htmlunit.javascript.configuration.JsxSetter;
40  import org.htmlunit.javascript.configuration.JsxSymbol;
41  
42  /**
43   * A JavaScript object for {@code DOMTokenList}.
44   *
45   * @author Ahmed Ashour
46   * @author Ronald Brill
47   * @author Marek Gawlicki
48   * @author Markus Winter
49   * @author Vladimir Babin
50   *
51   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList">MDN Documentation</a>
52   */
53  @JsxClass
54  public class DOMTokenList extends HtmlUnitScriptable {
55  
56      // the supported tokens of the sandbox attribute
57      private static final Set<String> SANDBOX_SUPPORTED_TOKENS = Set.of(
58              "allow-downloads", "allow-forms", "allow-modals", "allow-orientation-lock",
59              "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox", "allow-presentation",
60              "allow-same-origin", "allow-scripts", "allow-storage-access-by-user-activation",
61              "allow-top-navigation", "allow-top-navigation-by-user-activation",
62              "allow-top-navigation-to-custom-protocols");
63  
64      private static final String WHITESPACE_CHARS = " \t\r\n\u000C";
65  
66      private String attributeName_;
67  
68      /**
69       * Creates an instance.
70       */
71      public DOMTokenList() {
72          super();
73      }
74  
75      /**
76       * JavaScript constructor.
77       */
78      @JsxConstructor
79      public void jsConstructor() {
80          // nothing to do
81      }
82  
83      /**
84       * Creates an instance.
85       * @param node the node which contains the underlying string
86       * @param attributeName the attribute name of the DomElement of the specified node
87       */
88      public DOMTokenList(final Node node, final String attributeName) {
89          super();
90          setDomNode(node.getDomNodeOrDie(), false);
91          setParentScope(node.getParentScope());
92          setPrototype(getPrototype(getClass()));
93          attributeName_ = attributeName;
94      }
95  
96      /**
97       * Returns the {@code value} property.
98       * @return the value
99       */
100     @JsxGetter
101     public String getValue() {
102         final DomNode node = getDomNodeOrNull();
103         if (node != null) {
104             final DomAttr attr = (DomAttr) node.getAttributes().getNamedItem(attributeName_);
105             if (attr != null) {
106                 return attr.getValue();
107             }
108         }
109         return null;
110     }
111 
112     /**
113      * Sets the {@code value} property.
114      * @param value the new value
115      */
116     @JsxSetter
117     public void setValue(final String value) {
118         final DomNode node = getDomNodeOrNull();
119         if (node != null) {
120             updateAttribute(value);
121         }
122     }
123 
124     /**
125      * Returns the length property.
126      * @return the length
127      */
128     @JsxGetter
129     public int getLength() {
130         final String value = getValue();
131         if (org.htmlunit.util.StringUtils.isBlank(value)) {
132             return 0;
133         }
134 
135         return split(value).size();
136     }
137 
138     /**
139      * {@inheritDoc}
140      */
141     @Override
142     public String getDefaultValue(final Class<?> hint) {
143         if (getPrototype() == null) {
144             return (String) super.getDefaultValue(hint);
145         }
146 
147         // like toString(), the value of the attribute (not normalized)
148         return jsToString();
149     }
150 
151     /**
152      * Returns the value of the underlying attribute (the stringifier of DOMTokenList).
153      *
154      * @return the value or an empty string if the attribute is not set
155      */
156     @JsxFunction(functionName = "toString")
157     public String jsToString() {
158         final String value = getValue();
159         if (value == null) {
160             return "";
161         }
162         return value;
163     }
164 
165     /**
166      * Adds the given tokens to the list, omitting any that are already present.
167      *
168      * @param context the JavaScript context
169      * @param scope the scope
170      * @param thisObj the scriptable
171      * @param args the arguments passed into the method
172      * @param function the function
173      */
174     @JsxFunction
175     public static void add(final Context context, final VarScope scope,
176             final Scriptable thisObj, final Object[] args, final Function function) {
177         if (args.length > 0) {
178             final DOMTokenList list = (DOMTokenList) thisObj;
179             final List<String> parts = split(list.getValue());
180 
181             for (final Object arg : args) {
182                 final String token = JavaScriptEngine.toString(arg);
183 
184                 if (org.htmlunit.util.StringUtils.isEmptyOrNull(token)) {
185                     throw JavaScriptEngine.asJavaScriptException(
186                             (HtmlUnitScriptable) getTopLevelScope(scope).getGlobalThis(),
187                             "DOMTokenList: add() does not support empty tokens",
188                             DOMException.SYNTAX_ERR);
189                 }
190                 if (StringUtils.containsAny(token, WHITESPACE_CHARS)) {
191                     throw JavaScriptEngine.asJavaScriptException(
192                             (HtmlUnitScriptable) getTopLevelScope(scope).getGlobalThis(),
193                             "DOMTokenList: add() does not support whitespace chars in tokens",
194                             DOMException.INVALID_CHARACTER_ERR);
195                 }
196 
197                 if (!parts.contains(token)) {
198                     parts.add(token);
199                 }
200             }
201             list.updateAttribute(String.join(" ", parts));
202         }
203     }
204 
205     /**
206      * Removes the specified tokens from the underlying string.
207      *
208      * @param context the JavaScript context
209      * @param scope the scope
210      * @param thisObj the scriptable
211      * @param args the arguments passed into the method
212      * @param function the function
213      */
214     @JsxFunction
215     public static void remove(final Context context, final VarScope scope,
216             final Scriptable thisObj, final Object[] args, final Function function) {
217         final DOMTokenList list = (DOMTokenList) thisObj;
218 
219         final String value = list.getValue();
220         if (value == null) {
221             return;
222         }
223 
224         if (args.length > 0) {
225             final List<String> parts = split(list.getValue());
226 
227             for (final Object arg : args) {
228                 final String token = JavaScriptEngine.toString(arg);
229 
230                 if (org.htmlunit.util.StringUtils.isEmptyOrNull(token)) {
231                     throw JavaScriptEngine.asJavaScriptException(
232                             (HtmlUnitScriptable) getTopLevelScope(scope).getGlobalThis(),
233                             "DOMTokenList: remove() does not support empty tokens",
234                             DOMException.SYNTAX_ERR);
235                 }
236                 if (StringUtils.containsAny(token, WHITESPACE_CHARS)) {
237                     throw JavaScriptEngine.asJavaScriptException(
238                             (HtmlUnitScriptable) getTopLevelScope(scope).getGlobalThis(),
239                             "DOMTokenList: remove() does not support whitespace chars in tokens",
240                             DOMException.INVALID_CHARACTER_ERR);
241                 }
242 
243                 parts.remove(token);
244             }
245             list.updateAttribute(String.join(" ", parts));
246         }
247     }
248 
249     /**
250      * Replaces an existing token with a new token. If the first token doesn't exist, replace()
251      * returns false immediately, without adding the new token to the token list.
252      * @param oldToken a string representing the token you want to replace
253      * @param newToken a string representing the token you want to replace oldToken with
254      * @return true if oldToken was successfully replaced, or false if not
255      */
256     @JsxFunction
257     public boolean replace(final String oldToken, final String newToken) {
258         if (org.htmlunit.util.StringUtils.isEmptyOrNull(oldToken)) {
259             throw JavaScriptEngine.asJavaScriptException(
260                     getWindow(),
261                     "Empty oldToken not allowed",
262                     DOMException.SYNTAX_ERR);
263         }
264         if (StringUtils.containsAny(oldToken, WHITESPACE_CHARS)) {
265             throw JavaScriptEngine.asJavaScriptException(
266                     getWindow(),
267                     "DOMTokenList: replace() oldToken contains whitespace",
268                     DOMException.INVALID_CHARACTER_ERR);
269         }
270 
271         if (org.htmlunit.util.StringUtils.isEmptyOrNull(newToken)) {
272             throw JavaScriptEngine.asJavaScriptException(
273                     getWindow(),
274                     "Empty newToken not allowed",
275                     DOMException.SYNTAX_ERR);
276         }
277         if (StringUtils.containsAny(newToken, WHITESPACE_CHARS)) {
278             throw JavaScriptEngine.asJavaScriptException(
279                     getWindow(),
280                     "DOMTokenList: replace() newToken contains whitespace",
281                     DOMException.INVALID_CHARACTER_ERR);
282         }
283 
284         final String value = getValue();
285         if (value == null) {
286             return false;
287         }
288         final List<String> parts = split(value);
289         final int pos = parts.indexOf(oldToken);
290         if (pos == -1) {
291             return false;
292         }
293 
294         parts.set(pos, newToken);
295         updateAttribute(String.join(" ", parts));
296         return true;
297     }
298 
299     /**
300      * Toggles the token, adding or removing it.
301      * @param token the token to add or remove
302      * @param force if {@code true}, only adds the token; if {@code false}, only removes it;
303      *        if not specified, the token is toggled
304      * @return whether the string now contains the token or not
305      */
306     @JsxFunction
307     public boolean toggle(final String token, final Object force) {
308         if (org.htmlunit.util.StringUtils.isEmptyOrNull(token)) {
309             throw JavaScriptEngine.asJavaScriptException(
310                     getWindow(),
311                     "DOMTokenList: toggle() does not support empty tokens",
312                     DOMException.SYNTAX_ERR);
313         }
314         if (StringUtils.containsAny(token, WHITESPACE_CHARS)) {
315             throw JavaScriptEngine.asJavaScriptException(
316                     getWindow(),
317                     "DOMTokenList: toggle() does not support whitespace chars in tokens",
318                     DOMException.INVALID_CHARACTER_ERR);
319         }
320 
321         final List<String> parts = split(getValue());
322         final boolean present = parts.contains(token);
323 
324         // looks strange but it's what the spec says
325         final boolean add = JavaScriptEngine.isUndefined(force) ? !present : JavaScriptEngine.toBoolean(force);
326 
327         if (add && !present) {
328             parts.add(token);
329             updateAttribute(String.join(" ", parts));
330         }
331         else if (!add && present) {
332             parts.remove(token);
333             updateAttribute(String.join(" ", parts));
334         }
335         return add;
336     }
337 
338     /**
339      * Checks if the specified token is contained in the underlying string.
340      * @param token the token to add
341      * @return true if the underlying string contains token, otherwise false
342      */
343     @JsxFunction
344     public boolean contains(final String token) {
345         if (org.htmlunit.util.StringUtils.isBlank(token)) {
346             return false;
347         }
348 
349         if (org.htmlunit.util.StringUtils.isEmptyOrNull(token)) {
350             throw JavaScriptEngine.reportRuntimeError("DOMTokenList: contains() does not support empty tokens");
351         }
352         if (StringUtils.containsAny(token, WHITESPACE_CHARS)) {
353             throw JavaScriptEngine.reportRuntimeError(
354                     "DOMTokenList: contains() does not support whitespace chars in tokens");
355         }
356 
357         final List<String> parts = split(getValue());
358         return parts.contains(token);
359     }
360 
361     /**
362      * Returns whether the token is one of the supported tokens of the underlying attribute.
363      * Only the {@code sandbox} attribute has supported tokens in HtmlUnit; for all other
364      * attributes a TypeError is thrown.
365      *
366      * @param token the token to check
367      * @return true if the token is supported
368      */
369     @JsxFunction
370     public boolean supports(final String token) {
371         if (!BaseFrameElement.SANDBOX_ATTRIBUTE.equals(attributeName_)) {
372             throw JavaScriptEngine.typeError("DOMTokenList has no supported tokens.");
373         }
374         return SANDBOX_SUPPORTED_TOKENS.contains(org.htmlunit.util.StringUtils.toRootLowerCase(token));
375     }
376 
377     /**
378      * Returns the item at the specified index.
379      * @param index the index of the item
380      * @return the item
381      */
382     @JsxFunction
383     public String item(final int index) {
384         if (index < 0) {
385             return null;
386         }
387 
388         final String value = getValue();
389         if (org.htmlunit.util.StringUtils.isEmptyOrNull(value)) {
390             return null;
391         }
392 
393         final List<String> parts = split(value);
394         if (index < parts.size()) {
395             return parts.get(index);
396         }
397 
398         return null;
399     }
400 
401     /**
402      * Returns an Iterator allowing to go through all keys contained in this object.
403      * @return a NativeArrayIterator
404      */
405     @JsxFunction
406     public Scriptable keys() {
407         return JavaScriptEngine.newArrayIteratorTypeKeys(getParentScope(), this);
408     }
409 
410     /**
411      * Returns an Iterator allowing to go through all keys contained in this object.
412      * @return a NativeArrayIterator
413      */
414     @JsxFunction
415     @JsxSymbol(symbolName = "iterator")
416     public Scriptable values() {
417         return JavaScriptEngine.newArrayIteratorTypeValues(getParentScope(), this);
418     }
419 
420     /**
421      * Returns an Iterator allowing to go through all key/value pairs contained in this object.
422      * @return a NativeArrayIterator
423      */
424     @JsxFunction
425     public Scriptable entries() {
426         return JavaScriptEngine.newArrayIteratorTypeEntries(getParentScope(), this);
427     }
428 
429     /**
430      * Calls the {@code callback} given in parameter once for each value in the list.
431      * @param callback function to execute for each element
432      */
433     @JsxFunction
434     public void forEach(final Object callback) {
435         if (!(callback instanceof Function function)) {
436             throw JavaScriptEngine.typeError(
437                     "Foreach callback '" + JavaScriptEngine.toString(callback) + "' is not a function");
438         }
439 
440         final String value = getValue();
441         if (org.htmlunit.util.StringUtils.isEmptyOrNull(value)) {
442             return;
443         }
444 
445         final WebClient client = getWindow().getWebWindow().getWebClient();
446         final HtmlUnitContextFactory cf = client.getJavaScriptEngine().getContextFactory();
447 
448         final ContextAction<Object> contextAction = cx -> {
449             final VarScope scope = getParentScope();
450 
451             List<String> parts = split(value);
452             final int size = parts.size();
453             int i = 0;
454             while (i < size && i < parts.size()) {
455                 function.call(cx, scope, this, new Object[] {parts.get(i), i, this});
456 
457                 // refresh
458                 parts = split(getValue());
459                 i++;
460             }
461             return null;
462         };
463         cf.call(contextAction);
464     }
465 
466     /**
467      * {@inheritDoc}
468      */
469     @Override
470     protected int getIndexedPropertyCount() {
471         return getLength();
472     }
473 
474     /**
475      * {@inheritDoc}
476      */
477     @Override
478     public Object get(final int index, final Scriptable start) {
479         final Object value = item(index);
480         if (value == null) {
481             return JavaScriptEngine.UNDEFINED;
482         }
483         return value;
484     }
485 
486     private void updateAttribute(final String value) {
487         final DomElement domNode = (DomElement) getDomNodeOrDie();
488 
489         // always create a new one because the old one is used later for the mutation observer
490         // to get the old value from
491         final DomAttr attr = domNode.getPage().createAttribute(attributeName_);
492         attr.setValue(value);
493         domNode.setAttributeNode(attr);
494     }
495 
496     private static List<String> split(final String value) {
497         if (org.htmlunit.util.StringUtils.isEmptyOrNull(value)) {
498             return new ArrayList<>();
499         }
500 
501         final String[] parts = StringUtils.split(value, WHITESPACE_CHARS);
502 
503         // usually a short list, no index needed
504         final List<String> result = new ArrayList<>();
505         for (final String part : parts) {
506             if (!result.contains(part)) {
507                 result.add(part);
508             }
509         }
510         return result;
511     }
512 }