| 72 | } |
| 73 | |
| 74 | void JavaScriptWorker::doPostInit() { |
| 75 | auto weakSelf = weakRef(this); |
| 76 | // Set up globals in the worker runtime |
| 77 | // - onmessage |
| 78 | // - postMessage |
| 79 | // - close |
| 80 | // - location, https://developer.mozilla.org/en-US/docs/Web/API/WorkerLocation, only href and search are populated |
| 81 | _runtime->setValueToGlobalObject(STRING_LITERAL("onmessage"), Value::undefined()); |
| 82 | auto postMessageFunc = [weakSelf](const ValueFunctionCallContext& callContext) -> Value { |
| 83 | auto self = weakSelf.lock(); |
| 84 | if (self && !self->_closed) { |
| 85 | dispatchMessage(self->_hostOnMessage, callContext.getParameter(0)); |
| 86 | } |
| 87 | return Value::undefined(); |
| 88 | }; |
| 89 | _runtime->setValueToGlobalObject(STRING_LITERAL("postMessage"), |
| 90 | Value(makeShared<ValueFunctionWithCallable>(postMessageFunc))); |
| 91 | auto closeFunc = [weakSelf](const ValueFunctionCallContext& callContext) -> Value { |
| 92 | auto self = weakSelf.lock(); |
| 93 | if (self) { |
| 94 | self->close(); |
| 95 | } |
| 96 | return Value::undefined(); |
| 97 | }; |
| 98 | |
| 99 | _runtime->setValueToGlobalObject(STRING_LITERAL("close"), Value(makeShared<ValueFunctionWithCallable>(closeFunc))); |
| 100 | |
| 101 | auto queryStartIndex = _url.indexOf('?'); |
| 102 | auto scriptUrl = queryStartIndex.has_value() ? _url.substring(0, queryStartIndex.value()) : _url; |
| 103 | auto location = makeShared<ValueMap>(); |
| 104 | (*location)[STRING_LITERAL("href")] = Value(_url); |
| 105 | (*location)[STRING_LITERAL("search")] = |
| 106 | Value(queryStartIndex.has_value() ? _url.substring(queryStartIndex.value()) : STRING_LITERAL("")); |
| 107 | _runtime->setValueToGlobalObject(STRING_LITERAL("location"), Value(location)); |
| 108 | |
| 109 | // Evaluate the worker script |
| 110 | auto result = _runtime->evalModuleSync(scriptUrl, false); |
| 111 | } |
| 112 | |
| 113 | void JavaScriptWorker::doSetHostOnMessage(const Ref<ValueFunction>& func) { |
| 114 | _hostOnMessage = func; |
no test coverage detected