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_PERFORMANCE_OBSERVER_ENTRY_TYPES_FF;
18  import static org.htmlunit.BrowserVersionFeatures.JS_PERFORMANCE_OBSERVER_ENTRY_TYPES_FROZEN;
19  
20  import org.htmlunit.BrowserVersion;
21  import org.htmlunit.corejs.javascript.Function;
22  import org.htmlunit.corejs.javascript.Scriptable;
23  import org.htmlunit.corejs.javascript.ScriptableObject;
24  import org.htmlunit.corejs.javascript.SymbolKey;
25  import org.htmlunit.corejs.javascript.VarScope;
26  import org.htmlunit.javascript.HtmlUnitScriptable;
27  import org.htmlunit.javascript.JavaScriptEngine;
28  import org.htmlunit.javascript.configuration.JsxClass;
29  import org.htmlunit.javascript.configuration.JsxConstructor;
30  import org.htmlunit.javascript.configuration.JsxFunction;
31  import org.htmlunit.javascript.configuration.JsxStaticGetter;
32  import org.htmlunit.javascript.host.dom.DOMException;
33  
34  /**
35   * JavaScript host object for {@code PerformanceObserver}.
36   * <p>
37   * HtmlUnit does not record performance entries, so the callback is never invoked.
38   * This implementation provides the API surface and the argument validation of real
39   * browsers, so scripts that use the observer (e.g. for feature detection) do not fail.
40   * </p>
41   *
42   * @author Ronald Brill
43   *
44   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver">MDN Documentation</a>
45   * @see <a href="https://w3c.github.io/performance-timeline/#the-performanceobserver-interface">W3C spec</a>
46   */
47  @JsxClass
48  public class PerformanceObserver extends HtmlUnitScriptable {
49  
50      // Object[] (not String[]) because the array is handed to Rhino, which may store other values
51  
52      /** The entry types supported by Chrome/Edge. */
53      private static final Object[] SUPPORTED_ENTRY_TYPES = {
54          "element", "event", "first-input", "interaction-contentful-paint", "largest-contentful-paint",
55          "layout-shift", "long-animation-frame", "longtask", "mark", "measure", "navigation", "paint",
56          "resource", "soft-navigation", "visibility-state"};
57  
58      /** The entry types supported by Firefox. */
59      private static final Object[] SUPPORTED_ENTRY_TYPES_FF = {
60          "event", "first-input", "largest-contentful-paint", "mark", "measure", "navigation", "paint",
61          "resource"};
62  
63      /** The key of the cached (frozen) supportedEntryTypes array. */
64      private static final String SUPPORTED_ENTRY_TYPES_KEY = "PerformanceObserver.supportedEntryTypes";
65  
66      private enum ObserverType { UNDEFINED, SINGLE, MULTIPLE }
67  
68      private ObserverType observerType_ = ObserverType.UNDEFINED;
69  
70      /**
71       * Creates an instance of this object.
72       * @param callback the function called when observed entries are recorded
73       */
74      @JsxConstructor
75      public void jsConstructor(final Object callback) {
76          if (!(callback instanceof Function)) {
77              throw JavaScriptEngine.typeError(
78                      "Failed to construct 'PerformanceObserver': "
79                      + "The callback provided as parameter 1 is not a function.");
80          }
81      }
82  
83      /**
84       * Starts observing the given entry types.
85       * @param options the options ({@code entryTypes}, or {@code type} and {@code buffered})
86       */
87      @JsxFunction
88      public void observe(final Object options) {
89          Object entryTypes = null;
90          Object type = null;
91          if (options instanceof Scriptable optionsScriptable) {
92              entryTypes = getOptionValue(optionsScriptable, "entryTypes");
93              type = getOptionValue(optionsScriptable, "type");
94          }
95  
96          // WebIDL sequence<DOMString>: only iterable objects (e.g. arrays, sets) can be converted
97          if (entryTypes != null
98                  && !(entryTypes instanceof Scriptable entryTypesScriptable
99                          && ScriptableObject.hasProperty(entryTypesScriptable, SymbolKey.ITERATOR))) {
100             throw JavaScriptEngine.typeError(
101                     "Failed to execute 'observe' on 'PerformanceObserver': "
102                     + "Failed to read the 'entryTypes' property from 'PerformanceObserverInit': "
103                     + "The provided value cannot be converted to a sequence.");
104         }
105 
106         if (entryTypes == null && type == null) {
107             throw JavaScriptEngine.typeError(
108                     "Failed to execute 'observe' on 'PerformanceObserver': "
109                     + "An observe() call must include either entryTypes or type arguments.");
110         }
111         if (entryTypes != null && type != null) {
112             throw JavaScriptEngine.typeError(
113                     "Failed to execute 'observe' on 'PerformanceObserver': "
114                     + "An observe() call must not include both entryTypes and type arguments.");
115         }
116 
117         final ObserverType requested = entryTypes != null ? ObserverType.MULTIPLE : ObserverType.SINGLE;
118         if (observerType_ != ObserverType.UNDEFINED && observerType_ != requested) {
119             throw JavaScriptEngine.asJavaScriptException(this,
120                     "Failed to execute 'observe' on 'PerformanceObserver': "
121                     + "This observer has already been used with "
122                     + (observerType_ == ObserverType.MULTIPLE ? "entryTypes" : "type")
123                     + " and cannot be changed.",
124                     DOMException.INVALID_MODIFICATION_ERR);
125         }
126         observerType_ = requested;
127 
128         // browsers silently ignore unsupported entry types (console warning only);
129         // HtmlUnit does not record any entries at all
130     }
131 
132     /**
133      * Stops the observer from receiving performance entries.
134      */
135     @JsxFunction
136     public void disconnect() {
137         // nothing to do, HtmlUnit does not record performance entries
138     }
139 
140     /**
141      * Returns the performance entries stored in the observer, emptying it out.
142      * @return an empty array, HtmlUnit does not record performance entries
143      */
144     @JsxFunction
145     public Scriptable takeRecords() {
146         return JavaScriptEngine.newArray(getParentScope(), 0);
147     }
148 
149     /**
150      * Returns the entry types supported by the browser.
151      *
152      * @param thisObj the scriptable
153      * @return the entry types supported by the browser
154      */
155     @JsxStaticGetter
156     public static Scriptable getSupportedEntryTypes(final Scriptable thisObj) {
157         final Window window = getWindow(thisObj);
158         final BrowserVersion browserVersion = window.getBrowserVersion();
159 
160         if (!browserVersion.hasFeature(JS_PERFORMANCE_OBSERVER_ENTRY_TYPES_FROZEN)) {
161             // a new (modifiable) array for every call
162             return newEntryTypesArray(thisObj, browserVersion);
163         }
164 
165         // FrozenArray<DOMString>; the same object is returned for every call,
166         // cached at the PerformanceObserver constructor of the window
167         final ScriptableObject cacheHolder = thisObj instanceof ScriptableObject holder ? holder : null;
168         if (cacheHolder != null
169                 && cacheHolder.getAssociatedValue(SUPPORTED_ENTRY_TYPES_KEY) instanceof Scriptable cached) {
170             return cached;
171         }
172 
173         final Scriptable result = newEntryTypesArray(thisObj, browserVersion);
174         final Object objectCtor = ScriptableObject.getProperty(window, "Object");
175         if (objectCtor instanceof Scriptable objectCtorScriptable) {
176             ScriptableObject.callMethod(objectCtorScriptable, "freeze", new Object[] {result});
177         }
178         if (cacheHolder != null) {
179             cacheHolder.associateValue(SUPPORTED_ENTRY_TYPES_KEY, result);
180         }
181         return result;
182     }
183 
184     /**
185      * Creates a new array containing the entry types supported by the given browser.
186      *
187      * @param thisObj the scriptable (used to determine the scope)
188      * @param browserVersion the browser version
189      * @return a new array containing the supported entry types
190      */
191     private static Scriptable newEntryTypesArray(final Scriptable thisObj, final BrowserVersion browserVersion) {
192         final Object[] entryTypes = browserVersion.hasFeature(JS_PERFORMANCE_OBSERVER_ENTRY_TYPES_FF)
193                 ? SUPPORTED_ENTRY_TYPES_FF
194                 : SUPPORTED_ENTRY_TYPES;
195 
196         final VarScope scope = ScriptableObject.getTopLevelScope(thisObj.getParentScope());
197         return JavaScriptEngine.newArray(scope, entryTypes.clone());
198     }
199 
200     /**
201      * Returns the value of the given member of the options dictionary;
202      * WebIDL dictionary semantics: a member set to {@code undefined} counts as absent.
203      *
204      * @param options the options dictionary
205      * @param name the name of the member
206      * @return the value of the member or {@code null} if the member is absent
207      */
208     private static Object getOptionValue(final Scriptable options, final String name) {
209         final Object value = ScriptableObject.getProperty(options, name);
210         if (value == Scriptable.NOT_FOUND || JavaScriptEngine.isUndefined(value)) {
211             return null;
212         }
213         return value;
214     }
215 }