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