1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.worker;
16
17 import org.htmlunit.WebClient;
18 import org.htmlunit.corejs.javascript.Context;
19 import org.htmlunit.corejs.javascript.Function;
20 import org.htmlunit.corejs.javascript.Scriptable;
21 import org.htmlunit.corejs.javascript.VarScope;
22 import org.htmlunit.javascript.JavaScriptEngine;
23 import org.htmlunit.javascript.configuration.JsxClass;
24 import org.htmlunit.javascript.configuration.JsxConstructor;
25 import org.htmlunit.javascript.configuration.JsxFunction;
26 import org.htmlunit.javascript.configuration.JsxGetter;
27 import org.htmlunit.javascript.configuration.JsxSetter;
28 import org.htmlunit.javascript.host.Window;
29 import org.htmlunit.javascript.host.event.Event;
30 import org.htmlunit.javascript.host.event.EventTarget;
31
32
33
34
35
36
37
38
39 @JsxClass
40 public class Worker extends EventTarget {
41
42 private final DedicatedWorkerGlobalScope workerScope_;
43
44
45
46
47 public Worker() {
48
49 super();
50 workerScope_ = null;
51 }
52
53 private Worker(final Context cx, final VarScope scope,
54 final Window owningWindow, final String url,
55 final Scriptable options) throws Exception {
56 super();
57 setParentScope(scope);
58 setPrototype(getPrototype(getClass()));
59
60 final WebClient webClient = getWindow().getWebWindow().getWebClient();
61 String name = null;
62 if (options != null && options.has("name", options)) {
63 name = JavaScriptEngine.toString(options.get("name", options));
64 }
65 workerScope_ = new DedicatedWorkerGlobalScope(owningWindow, cx, webClient, name, this);
66
67 workerScope_.loadAndExecute(webClient, url, null, false);
68 }
69
70
71
72
73
74
75
76
77
78
79
80 @JsxConstructor
81 public static Worker jsConstructor(final Context cx, final VarScope scope,
82 final Object[] args, final Function ctorObj, final boolean inNewExpr) throws Exception {
83 if (args.length < 1 || args.length > 2) {
84 throw JavaScriptEngine.reportRuntimeError(
85 "Worker Error: constructor must have one or two parameters.");
86 }
87
88 final String url = JavaScriptEngine.toString(args[0]);
89 Scriptable options = null;
90 if (args.length > 1 && args[1] instanceof Scriptable scriptable) {
91 options = scriptable;
92 }
93 return new Worker(cx, scope, getWindow(ctorObj), url, options);
94 }
95
96
97
98
99
100 @JsxFunction
101 public void postMessage(final Object message) {
102 workerScope_.messagePosted(message);
103 }
104
105
106
107
108
109 @JsxFunction
110 public void terminate() {
111
112 }
113
114
115
116
117
118 @JsxSetter
119 public void setOnmessage(final Object onmessage) {
120 getEventListenersContainer().setEventHandler(Event.TYPE_MESSAGE, onmessage);
121 }
122
123
124
125
126
127 @JsxGetter
128 public Function getOnmessage() {
129 return getEventListenersContainer().getEventHandler(Event.TYPE_MESSAGE);
130 }
131 }