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.worker;
16  
17  import java.net.URL;
18  
19  import org.htmlunit.WebClient;
20  import org.htmlunit.corejs.javascript.Context;
21  import org.htmlunit.corejs.javascript.ContextAction;
22  import org.htmlunit.corejs.javascript.Function;
23  import org.htmlunit.corejs.javascript.Scriptable;
24  import org.htmlunit.corejs.javascript.VarScope;
25  import org.htmlunit.html.HtmlPage;
26  import org.htmlunit.html.csp.ContentSecurityPolicy;
27  import org.htmlunit.javascript.HtmlUnitContextFactory;
28  import org.htmlunit.javascript.JavaScriptEngine;
29  import org.htmlunit.javascript.configuration.JsxClass;
30  import org.htmlunit.javascript.configuration.JsxConstructor;
31  import org.htmlunit.javascript.configuration.JsxFunction;
32  import org.htmlunit.javascript.configuration.JsxGetter;
33  import org.htmlunit.javascript.configuration.JsxSetter;
34  import org.htmlunit.javascript.host.Window;
35  import org.htmlunit.javascript.host.event.Event;
36  import org.htmlunit.javascript.host.event.EventTarget;
37  
38  /**
39   * JavaScript host object for {@code Worker}.
40   *
41   * @author Ahmed Ashour
42   * @author Marc Guillemot
43   * @author Ronald Brill
44   *
45   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">MDN Documentation</a>
46   */
47  @JsxClass
48  public class Worker extends EventTarget {
49  
50      private final DedicatedWorkerGlobalScope workerScope_;
51  
52      /**
53       * Default constructor.
54       */
55      public Worker() {
56          // prototype constructor
57          super();
58          workerScope_ = null;
59      }
60  
61      private Worker(final Context cx, final VarScope scope,
62                      final Window owningWindow, final String url,
63                      final Scriptable options) throws Exception {
64          super();
65          setParentScope(getTopLevelScope(scope));
66          setPrototype(getPrototype(getClass()));
67  
68          final WebClient webClient = getWindow().getWebWindow().getWebClient();
69          String name = null;
70          if (options != null && options.has("name", options)) {
71              name = JavaScriptEngine.toString(options.get("name", options));
72          }
73          workerScope_ = new DedicatedWorkerGlobalScope(owningWindow, cx, webClient, name, this);
74  
75          final HtmlPage page = (HtmlPage) owningWindow.getDocument().getPage();
76          // upgrade-insecure-requests of the Content-Security-Policy
77          final URL resolvedUrl = page.getFullyQualifiedUrl(url);
78          final URL fullUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, resolvedUrl);
79          if (!ContentSecurityPolicy.allowsWorker(page, fullUrl)) {
80              // like the browsers, the worker is not started and the error event is fired (async)
81              final ContextAction<Object> action = c -> {
82                  dispatchEvent(new Event(this, Event.TYPE_ERROR));
83                  return null;
84              };
85              final HtmlUnitContextFactory cf = webClient.getJavaScriptEngine().getContextFactory();
86              owningWindow.getWebWindow().getJobManager()
87                      .addJob(new WorkerJob(cf, action, "worker blocked by the Content-Security-Policy"), page);
88              return;
89          }
90  
91          workerScope_.loadAndExecute(webClient, fullUrl == resolvedUrl ? url : fullUrl.toExternalForm(), null, false);
92      }
93  
94      /**
95       * Creates an instance of this object.
96       *
97       * @param cx the current context
98       * @param scope the scope
99       * @param args the constructor arguments
100      * @param ctorObj the function object
101      * @param inNewExpr whether invoked via {@code new}
102      * @return the new {@code Worker} instance
103      * @throws Exception in case of problem
104      */
105     @JsxConstructor
106     public static Worker jsConstructor(final Context cx, final VarScope scope,
107             final Object[] args, final Function ctorObj, final boolean inNewExpr) throws Exception {
108         if (args.length < 1 || args.length > 2) {
109             throw JavaScriptEngine.reportRuntimeError(
110                     "Worker Error: constructor must have one or two parameters.");
111         }
112 
113         final String url = JavaScriptEngine.toString(args[0]);
114         Scriptable options = null;
115         if (args.length > 1 && args[1] instanceof Scriptable scriptable) {
116             options = scriptable;
117         }
118         return new Worker(cx, scope, getWindow(ctorObj), url, options);
119     }
120 
121     /**
122      * Posts the provided message to the worker's execution context.
123      *
124      * @param message the message to post
125      */
126     @JsxFunction
127     public void postMessage(final Object message) {
128         workerScope_.messagePosted(message);
129     }
130 
131     /**
132      * Immediately terminates the worker without giving it the opportunity to
133      * finish any currently executing operations.
134      */
135     @JsxFunction
136     public void terminate() {
137         // TODO
138     }
139 
140     /**
141      * Sets the {@code onmessage} event handler.
142      *
143      * @param onmessage the new {@code onmessage} event handler
144      */
145     @JsxSetter
146     public void setOnmessage(final Object onmessage) {
147         getEventListenersContainer().setEventHandler(Event.TYPE_MESSAGE, onmessage);
148     }
149 
150     /**
151      * Returns the {@code onmessage} event handler.
152      *
153      * @return the {@code onmessage} event handler
154      */
155     @JsxGetter
156     public Function getOnmessage() {
157         return getEventListenersContainer().getEventHandler(Event.TYPE_MESSAGE);
158     }
159 
160     /**
161      * Sets the {@code onerror} event handler.
162      *
163      * @param onerror the new {@code onerror} event handler
164      */
165     @JsxSetter
166     public void setOnerror(final Object onerror) {
167         getEventListenersContainer().setEventHandler(Event.TYPE_ERROR, onerror);
168     }
169 
170     /**
171      * Returns the {@code onerror} event handler.
172      *
173      * @return the {@code onerror} event handler
174      */
175     @JsxGetter
176     public Function getOnerror() {
177         return getEventListenersContainer().getEventHandler(Event.TYPE_ERROR);
178     }
179 }