1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://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
16 #include "napi_webview_controller.h"
17
18 #include <arpa/inet.h>
19 #include <cctype>
20 #include <climits>
21 #include <cstdint>
22 #include <regex>
23 #include <securec.h>
24 #include <unistd.h>
25 #include <uv.h>
26
27 #include "application_context.h"
28 #include "business_error.h"
29 #include "napi_parse_utils.h"
30 #include "native_engine/native_engine.h"
31 #include "nweb.h"
32 #include "nweb_adapter_helper.h"
33 #include "nweb_helper.h"
34 #include "nweb_init_params.h"
35 #include "nweb_log.h"
36 #include "ohos_adapter_helper.h"
37 #include "parameters.h"
38 #include "pixel_map.h"
39 #include "pixel_map_napi.h"
40 #include "web_errors.h"
41 #include "webview_javascript_execute_callback.h"
42
43 #include "web_download_delegate.h"
44 #include "web_download_manager.h"
45 #include "arkweb_scheme_handler.h"
46 #include "web_scheme_handler_request.h"
47
48 namespace OHOS {
49 namespace NWeb {
50 using namespace NWebError;
51 using NWebError::NO_ERROR;
52
53 namespace {
54 constexpr uint32_t URL_MAXIMUM = 2048;
55 constexpr uint32_t SOCKET_MAXIMUM = 6;
56 constexpr char URL_REGEXPR[] = "^http(s)?:\\/\\/.+";
57 constexpr size_t MAX_RESOURCES_COUNT = 30;
58 constexpr size_t MAX_RESOURCE_SIZE = 10 * 1024 * 1024;
59 constexpr size_t MAX_URL_TRUST_LIST_STR_LEN = 10 * 1024 * 1024; // 10M
60 constexpr size_t BFCACHE_DEFAULT_SIZE = 1;
61 constexpr size_t BFCACHE_DEFAULT_TIMETOLIVE = 600;
62 using WebPrintWriteResultCallback = std::function<void(std::string, uint32_t)>;
63
ParsePrepareUrl(napi_env env,napi_value urlObj,std::string & url)64 bool ParsePrepareUrl(napi_env env, napi_value urlObj, std::string& url)
65 {
66 napi_valuetype valueType = napi_null;
67 napi_typeof(env, urlObj, &valueType);
68
69 if (valueType == napi_string) {
70 NapiParseUtils::ParseString(env, urlObj, url);
71 if (url.size() > URL_MAXIMUM) {
72 WVLOG_E("The URL exceeds the maximum length of %{public}d", URL_MAXIMUM);
73 return false;
74 }
75
76 if (!regex_match(url, std::regex(URL_REGEXPR, std::regex_constants::icase))) {
77 WVLOG_E("ParsePrepareUrl error");
78 return false;
79 }
80
81 return true;
82 }
83
84 WVLOG_E("Unable to parse type from url object.");
85 return false;
86 }
87
ParseIP(napi_env env,napi_value urlObj,std::string & ip)88 bool ParseIP(napi_env env, napi_value urlObj, std::string& ip)
89 {
90 napi_valuetype valueType = napi_null;
91 napi_typeof(env, urlObj, &valueType);
92
93 if (valueType == napi_string) {
94 NapiParseUtils::ParseString(env, urlObj, ip);
95 if (ip == "") {
96 WVLOG_E("The IP is null");
97 return false;
98 }
99
100 unsigned char buf[sizeof(struct in6_addr)];
101 if ((inet_pton(AF_INET, ip.c_str(), buf) == 1) || (inet_pton(AF_INET6, ip.c_str(), buf) == 1)) {
102 return true;
103 }
104 WVLOG_E("IP error.");
105 return false;
106 }
107
108 WVLOG_E("Unable to parse type from ip object.");
109 return false;
110 }
111
GetArrayValueType(napi_env env,napi_value array,bool & isDouble)112 napi_valuetype GetArrayValueType(napi_env env, napi_value array, bool& isDouble)
113 {
114 uint32_t arrayLength = 0;
115 napi_get_array_length(env, array, &arrayLength);
116 napi_valuetype valueTypeFirst = napi_undefined;
117 napi_valuetype valueTypeCur = napi_undefined;
118 for (uint32_t i = 0; i < arrayLength; ++i) {
119 napi_value obj = nullptr;
120 napi_get_element(env, array, i, &obj);
121 napi_typeof(env, obj, &valueTypeCur);
122 if (i == 0) {
123 valueTypeFirst = valueTypeCur;
124 }
125 if (valueTypeCur != napi_string && valueTypeCur != napi_number && valueTypeCur != napi_boolean) {
126 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
127 return napi_undefined;
128 }
129 if (valueTypeCur != valueTypeFirst) {
130 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
131 return napi_undefined;
132 }
133 if (valueTypeFirst == napi_number) {
134 int32_t elementInt32 = 0;
135 double elementDouble = 0.0;
136 bool isReadValue32 = napi_get_value_int32(env, obj, &elementInt32) == napi_ok;
137 bool isReadDouble = napi_get_value_double(env, obj, &elementDouble) == napi_ok;
138 constexpr double MINIMAL_ERROR = 0.000001;
139 if (isReadValue32 && isReadDouble) {
140 isDouble = abs(elementDouble - elementInt32 * 1.0) > MINIMAL_ERROR;
141 } else if (isReadDouble) {
142 isDouble = true;
143 }
144 }
145 }
146 return valueTypeFirst;
147 }
148
SetArrayHandlerBoolean(napi_env env,napi_value array,WebMessageExt * webMessageExt)149 void SetArrayHandlerBoolean(napi_env env, napi_value array, WebMessageExt* webMessageExt)
150 {
151 std::vector<bool> outValue;
152 if (!NapiParseUtils::ParseBooleanArray(env, array, outValue)) {
153 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
154 return;
155 }
156 webMessageExt->SetBooleanArray(outValue);
157 }
158
SetArrayHandlerString(napi_env env,napi_value array,WebMessageExt * webMessageExt)159 void SetArrayHandlerString(napi_env env, napi_value array, WebMessageExt* webMessageExt)
160 {
161 std::vector<std::string> outValue;
162 if (!NapiParseUtils::ParseStringArray(env, array, outValue)) {
163 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
164 return;
165 }
166 webMessageExt->SetStringArray(outValue);
167 }
168
SetArrayHandlerInteger(napi_env env,napi_value array,WebMessageExt * webMessageExt)169 void SetArrayHandlerInteger(napi_env env, napi_value array, WebMessageExt* webMessageExt)
170 {
171 std::vector<int64_t> outValue;
172 if (!NapiParseUtils::ParseInt64Array(env, array, outValue)) {
173 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
174 return;
175 }
176 webMessageExt->SetInt64Array(outValue);
177 }
178
SetArrayHandlerDouble(napi_env env,napi_value array,WebMessageExt * webMessageExt)179 void SetArrayHandlerDouble(napi_env env, napi_value array, WebMessageExt* webMessageExt)
180 {
181 std::vector<double> outValue;
182 if (!NapiParseUtils::ParseDoubleArray(env, array, outValue)) {
183 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
184 return;
185 }
186 webMessageExt->SetDoubleArray(outValue);
187 }
188
GetWebviewController(napi_env env,napi_callback_info info)189 WebviewController* GetWebviewController(napi_env env, napi_callback_info info)
190 {
191 napi_value thisVar = nullptr;
192 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
193
194 WebviewController *webviewController = nullptr;
195 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
196 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
197 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
198 return nullptr;
199 }
200 return webviewController;
201 }
202
ParsePrepareRequestMethod(napi_env env,napi_value methodObj,std::string & method)203 bool ParsePrepareRequestMethod(napi_env env, napi_value methodObj, std::string& method)
204 {
205 napi_valuetype valueType = napi_null;
206 napi_typeof(env, methodObj, &valueType);
207
208 if (valueType == napi_string) {
209 NapiParseUtils::ParseString(env, methodObj, method);
210 if (method != "POST") {
211 WVLOG_E("The method %{public}s is not supported.", method.c_str());
212 return false;
213 }
214 return true;
215 }
216
217 WVLOG_E("Unable to parse type from method object.");
218 return false;
219 }
220
ParseHttpHeaders(napi_env env,napi_value headersArray,std::map<std::string,std::string> * headers)221 bool ParseHttpHeaders(napi_env env, napi_value headersArray, std::map<std::string, std::string>* headers)
222 {
223 bool isArray = false;
224 napi_is_array(env, headersArray, &isArray);
225 if (isArray) {
226 uint32_t arrayLength = INTEGER_ZERO;
227 napi_get_array_length(env, headersArray, &arrayLength);
228 for (uint32_t i = 0; i < arrayLength; ++i) {
229 std::string key;
230 std::string value;
231 napi_value obj = nullptr;
232 napi_value keyObj = nullptr;
233 napi_value valueObj = nullptr;
234 napi_get_element(env, headersArray, i, &obj);
235 if (napi_get_named_property(env, obj, "headerKey", &keyObj) != napi_ok) {
236 continue;
237 }
238 if (napi_get_named_property(env, obj, "headerValue", &valueObj) != napi_ok) {
239 continue;
240 }
241 if (!NapiParseUtils::ParseString(env, keyObj, key) || !NapiParseUtils::ParseString(env, valueObj, value)) {
242 WVLOG_E("Unable to parse string from headers array object.");
243 return false;
244 }
245 if (key.empty()) {
246 WVLOG_E("Key from headers is empty.");
247 return false;
248 }
249 (*headers)[key] = value;
250 }
251 } else {
252 WVLOG_E("Unable to parse type from headers array object.");
253 return false;
254 }
255 return true;
256 }
257
CheckCacheKey(napi_env env,const std::string & cacheKey)258 bool CheckCacheKey(napi_env env, const std::string& cacheKey)
259 {
260 for (char c : cacheKey) {
261 if (!isalnum(c)) {
262 WVLOG_E("BusinessError: 401. The character of 'cacheKey' must be number or letters.");
263 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
264 return false;
265 }
266 }
267 return true;
268 }
269
ParseCacheKeyList(napi_env env,napi_value cacheKeyArray,std::vector<std::string> * cacheKeyList)270 bool ParseCacheKeyList(napi_env env, napi_value cacheKeyArray, std::vector<std::string>* cacheKeyList)
271 {
272 bool isArray = false;
273 napi_is_array(env, cacheKeyArray, &isArray);
274 if (!isArray) {
275 WVLOG_E("Unable to parse type from CacheKey array object.");
276 return false;
277 }
278 uint32_t arrayLength = INTEGER_ZERO;
279 napi_get_array_length(env, cacheKeyArray, &arrayLength);
280 if (arrayLength == 0) {
281 WVLOG_E("cacheKey array length is invalid");
282 return false;
283 }
284 for (uint32_t i = 0; i < arrayLength; ++i) {
285 napi_value cacheKeyItem = nullptr;
286 napi_get_element(env, cacheKeyArray, i, &cacheKeyItem);
287 std::string cacheKeyStr;
288 if (!NapiParseUtils::ParseString(env, cacheKeyItem, cacheKeyStr)) {
289 WVLOG_E("Unable to parse string from cacheKey array object.");
290 return false;
291 }
292 if (cacheKeyStr.empty()) {
293 WVLOG_E("Cache Key is empty.");
294 return false;
295 }
296 for (char c : cacheKeyStr) {
297 if (!isalnum(c)) {
298 WVLOG_E("Cache Key is invalid.");
299 return false;
300 }
301 }
302 cacheKeyList->emplace_back(cacheKeyStr);
303 }
304 return true;
305 }
306
ParsePrefetchArgs(napi_env env,napi_value preArgs)307 std::shared_ptr<NWebEnginePrefetchArgs> ParsePrefetchArgs(napi_env env, napi_value preArgs)
308 {
309 napi_value urlObj = nullptr;
310 std::string url;
311 napi_get_named_property(env, preArgs, "url", &urlObj);
312 if (!ParsePrepareUrl(env, urlObj, url)) {
313 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
314 return nullptr;
315 }
316
317 napi_value methodObj = nullptr;
318 std::string method;
319 napi_get_named_property(env, preArgs, "method", &methodObj);
320 if (!ParsePrepareRequestMethod(env, methodObj, method)) {
321 WVLOG_E("BusinessError: 401. The type of 'method' must be string 'POST'.");
322 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
323 return nullptr;
324 }
325
326 napi_value formDataObj = nullptr;
327 std::string formData;
328 napi_get_named_property(env, preArgs, "formData", &formDataObj);
329 if (!NapiParseUtils::ParseString(env, formDataObj, formData)) {
330 WVLOG_E("BusinessError: 401. The type of 'formData' must be string.");
331 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
332 return nullptr;
333 }
334 std::shared_ptr<NWebEnginePrefetchArgs> prefetchArgs = std::make_shared<NWebEnginePrefetchArgsImpl>(
335 url, method, formData);
336 return prefetchArgs;
337 }
338
JsErrorCallback(napi_env env,napi_ref jsCallback,int32_t err)339 void JsErrorCallback(napi_env env, napi_ref jsCallback, int32_t err)
340 {
341 napi_value jsError = nullptr;
342 napi_value jsResult = nullptr;
343
344 jsError = BusinessError::CreateError(env, err);
345 napi_get_undefined(env, &jsResult);
346 napi_value args[INTEGER_TWO] = {jsError, jsResult};
347
348 napi_value callback = nullptr;
349 napi_value callbackResult = nullptr;
350 napi_get_reference_value(env, jsCallback, &callback);
351 napi_call_function(env, nullptr, callback, INTEGER_TWO, args, &callbackResult);
352 napi_delete_reference(env, jsCallback);
353 }
354
ParseRegisterJavaScriptProxyParam(napi_env env,size_t argc,napi_value * argv,RegisterJavaScriptProxyParam * param)355 bool ParseRegisterJavaScriptProxyParam(napi_env env, size_t argc, napi_value* argv,
356 RegisterJavaScriptProxyParam* param)
357 {
358 std::string objName;
359 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ONE], objName)) {
360 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
361 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "name", "string"));
362 return false;
363 }
364 std::vector<std::string> methodList;
365 if (!NapiParseUtils::ParseStringArray(env, argv[INTEGER_TWO], methodList)) {
366 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
367 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "methodList", "array"));
368 return false;
369 }
370 std::vector<std::string> asyncMethodList;
371 if (argc == INTEGER_FOUR && !NapiParseUtils::ParseStringArray(env, argv[INTEGER_THREE], asyncMethodList)) {
372 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
373 return false;
374 }
375 std::string permission;
376 if (argc == INTEGER_FIVE && !NapiParseUtils::ParseString(env, argv[INTEGER_FOUR], permission)) {
377 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
378 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "permission", "string"));
379 return false;
380 }
381 param->env = env;
382 param->obj = argv[INTEGER_ZERO];
383 param->objName = objName;
384 param->syncMethodList = methodList;
385 param->asyncMethodList = asyncMethodList;
386 param->permission = permission;
387 return true;
388 }
389
RemoveDownloadDelegateRef(napi_env env,napi_value thisVar)390 napi_value RemoveDownloadDelegateRef(napi_env env, napi_value thisVar)
391 {
392 WebviewController *webviewController = nullptr;
393 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
394 if (webviewController == nullptr || !webviewController->IsInit()) {
395 WVLOG_E("create message port failed, napi unwrap webviewController failed");
396 return nullptr;
397 }
398
399 WebDownloadManager::RemoveDownloadDelegateRef(webviewController->GetWebId());
400 return nullptr;
401 }
402 } // namespace
403
404 int32_t NapiWebviewController::maxFdNum_ = -1;
405 std::atomic<int32_t> NapiWebviewController::usedFd_ {0};
406 std::atomic<bool> g_inWebPageSnapshot {false};
407
408 thread_local napi_ref g_classWebMsgPort;
409 thread_local napi_ref g_historyListRef;
410 thread_local napi_ref g_webMsgExtClassRef;
411 thread_local napi_ref g_webPrintDocClassRef;
Init(napi_env env,napi_value exports)412 napi_value NapiWebviewController::Init(napi_env env, napi_value exports)
413 {
414 napi_property_descriptor properties[] = {
415 DECLARE_NAPI_STATIC_FUNCTION("initializeWebEngine", NapiWebviewController::InitializeWebEngine),
416 DECLARE_NAPI_STATIC_FUNCTION("setHttpDns", NapiWebviewController::SetHttpDns),
417 DECLARE_NAPI_STATIC_FUNCTION("setWebDebuggingAccess", NapiWebviewController::SetWebDebuggingAccess),
418 DECLARE_NAPI_STATIC_FUNCTION("setServiceWorkerWebSchemeHandler",
419 NapiWebviewController::SetServiceWorkerWebSchemeHandler),
420 DECLARE_NAPI_STATIC_FUNCTION("clearServiceWorkerWebSchemeHandler",
421 NapiWebviewController::ClearServiceWorkerWebSchemeHandler),
422 DECLARE_NAPI_FUNCTION("getWebDebuggingAccess", NapiWebviewController::InnerGetWebDebuggingAccess),
423 DECLARE_NAPI_FUNCTION("setWebId", NapiWebviewController::SetWebId),
424 DECLARE_NAPI_FUNCTION("jsProxy", NapiWebviewController::InnerJsProxy),
425 DECLARE_NAPI_FUNCTION("getCustomeSchemeCmdLine", NapiWebviewController::InnerGetCustomeSchemeCmdLine),
426 DECLARE_NAPI_FUNCTION("accessForward", NapiWebviewController::AccessForward),
427 DECLARE_NAPI_FUNCTION("accessBackward", NapiWebviewController::AccessBackward),
428 DECLARE_NAPI_FUNCTION("accessStep", NapiWebviewController::AccessStep),
429 DECLARE_NAPI_FUNCTION("clearHistory", NapiWebviewController::ClearHistory),
430 DECLARE_NAPI_FUNCTION("forward", NapiWebviewController::Forward),
431 DECLARE_NAPI_FUNCTION("backward", NapiWebviewController::Backward),
432 DECLARE_NAPI_FUNCTION("onActive", NapiWebviewController::OnActive),
433 DECLARE_NAPI_FUNCTION("onInactive", NapiWebviewController::OnInactive),
434 DECLARE_NAPI_FUNCTION("refresh", NapiWebviewController::Refresh),
435 DECLARE_NAPI_FUNCTION("zoomIn", NapiWebviewController::ZoomIn),
436 DECLARE_NAPI_FUNCTION("zoomOut", NapiWebviewController::ZoomOut),
437 DECLARE_NAPI_FUNCTION("getWebId", NapiWebviewController::GetWebId),
438 DECLARE_NAPI_FUNCTION("getUserAgent", NapiWebviewController::GetUserAgent),
439 DECLARE_NAPI_FUNCTION("getCustomUserAgent", NapiWebviewController::GetCustomUserAgent),
440 DECLARE_NAPI_FUNCTION("setCustomUserAgent", NapiWebviewController::SetCustomUserAgent),
441 DECLARE_NAPI_FUNCTION("getTitle", NapiWebviewController::GetTitle),
442 DECLARE_NAPI_FUNCTION("getPageHeight", NapiWebviewController::GetPageHeight),
443 DECLARE_NAPI_FUNCTION("backOrForward", NapiWebviewController::BackOrForward),
444 DECLARE_NAPI_FUNCTION("storeWebArchive", NapiWebviewController::StoreWebArchive),
445 DECLARE_NAPI_FUNCTION("createWebMessagePorts", NapiWebviewController::CreateWebMessagePorts),
446 DECLARE_NAPI_FUNCTION("postMessage", NapiWebviewController::PostMessage),
447 DECLARE_NAPI_FUNCTION("getHitTestValue", NapiWebviewController::GetHitTestValue),
448 DECLARE_NAPI_FUNCTION("requestFocus", NapiWebviewController::RequestFocus),
449 DECLARE_NAPI_FUNCTION("loadUrl", NapiWebviewController::LoadUrl),
450 DECLARE_NAPI_FUNCTION("postUrl", NapiWebviewController::PostUrl),
451 DECLARE_NAPI_FUNCTION("loadData", NapiWebviewController::LoadData),
452 DECLARE_NAPI_FUNCTION("getHitTest", NapiWebviewController::GetHitTest),
453 DECLARE_NAPI_FUNCTION("clearMatches", NapiWebviewController::ClearMatches),
454 DECLARE_NAPI_FUNCTION("searchNext", NapiWebviewController::SearchNext),
455 DECLARE_NAPI_FUNCTION("searchAllAsync", NapiWebviewController::SearchAllAsync),
456 DECLARE_NAPI_FUNCTION("clearSslCache", NapiWebviewController::ClearSslCache),
457 DECLARE_NAPI_FUNCTION("clearClientAuthenticationCache", NapiWebviewController::ClearClientAuthenticationCache),
458 DECLARE_NAPI_FUNCTION("stop", NapiWebviewController::Stop),
459 DECLARE_NAPI_FUNCTION("zoom", NapiWebviewController::Zoom),
460 DECLARE_NAPI_FUNCTION("registerJavaScriptProxy", NapiWebviewController::RegisterJavaScriptProxy),
461 DECLARE_NAPI_FUNCTION("innerCompleteWindowNew", NapiWebviewController::InnerCompleteWindowNew),
462 DECLARE_NAPI_FUNCTION("deleteJavaScriptRegister", NapiWebviewController::DeleteJavaScriptRegister),
463 DECLARE_NAPI_FUNCTION("runJavaScript", NapiWebviewController::RunJavaScript),
464 DECLARE_NAPI_FUNCTION("runJavaScriptExt", NapiWebviewController::RunJavaScriptExt),
465 DECLARE_NAPI_FUNCTION("getUrl", NapiWebviewController::GetUrl),
466 DECLARE_NAPI_FUNCTION("terminateRenderProcess", NapiWebviewController::TerminateRenderProcess),
467 DECLARE_NAPI_FUNCTION("getOriginalUrl", NapiWebviewController::GetOriginalUrl),
468 DECLARE_NAPI_FUNCTION("setNetworkAvailable", NapiWebviewController::SetNetworkAvailable),
469 DECLARE_NAPI_FUNCTION("innerGetWebId", NapiWebviewController::InnerGetWebId),
470 DECLARE_NAPI_FUNCTION("hasImage", NapiWebviewController::HasImage),
471 DECLARE_NAPI_FUNCTION("removeCache", NapiWebviewController::RemoveCache),
472 DECLARE_NAPI_FUNCTION("getFavicon", NapiWebviewController::GetFavicon),
473 DECLARE_NAPI_FUNCTION("getBackForwardEntries", NapiWebviewController::getBackForwardEntries),
474 DECLARE_NAPI_FUNCTION("serializeWebState", NapiWebviewController::SerializeWebState),
475 DECLARE_NAPI_FUNCTION("restoreWebState", NapiWebviewController::RestoreWebState),
476 DECLARE_NAPI_FUNCTION("pageDown", NapiWebviewController::ScrollPageDown),
477 DECLARE_NAPI_FUNCTION("pageUp", NapiWebviewController::ScrollPageUp),
478 DECLARE_NAPI_FUNCTION("scrollTo", NapiWebviewController::ScrollTo),
479 DECLARE_NAPI_FUNCTION("scrollBy", NapiWebviewController::ScrollBy),
480 DECLARE_NAPI_FUNCTION("slideScroll", NapiWebviewController::SlideScroll),
481 DECLARE_NAPI_FUNCTION("setScrollable", NapiWebviewController::SetScrollable),
482 DECLARE_NAPI_FUNCTION("getScrollable", NapiWebviewController::GetScrollable),
483 DECLARE_NAPI_STATIC_FUNCTION("customizeSchemes", NapiWebviewController::CustomizeSchemes),
484 DECLARE_NAPI_FUNCTION("innerSetHapPath", NapiWebviewController::InnerSetHapPath),
485 DECLARE_NAPI_FUNCTION("innerGetCertificate", NapiWebviewController::InnerGetCertificate),
486 DECLARE_NAPI_FUNCTION("setAudioMuted", NapiWebviewController::SetAudioMuted),
487 DECLARE_NAPI_FUNCTION("innerGetThisVar", NapiWebviewController::InnerGetThisVar),
488 DECLARE_NAPI_FUNCTION("prefetchPage", NapiWebviewController::PrefetchPage),
489 DECLARE_NAPI_FUNCTION("setDownloadDelegate", NapiWebviewController::SetDownloadDelegate),
490 DECLARE_NAPI_FUNCTION("startDownload", NapiWebviewController::StartDownload),
491 DECLARE_NAPI_STATIC_FUNCTION("prepareForPageLoad", NapiWebviewController::PrepareForPageLoad),
492 DECLARE_NAPI_FUNCTION("createWebPrintDocumentAdapter", NapiWebviewController::CreateWebPrintDocumentAdapter),
493 DECLARE_NAPI_STATIC_FUNCTION("setConnectionTimeout", NapiWebviewController::SetConnectionTimeout),
494 DECLARE_NAPI_FUNCTION("enableSafeBrowsing", NapiWebviewController::EnableSafeBrowsing),
495 DECLARE_NAPI_FUNCTION("isSafeBrowsingEnabled", NapiWebviewController::IsSafeBrowsingEnabled),
496 DECLARE_NAPI_FUNCTION("getSecurityLevel", NapiWebviewController::GetSecurityLevel),
497 DECLARE_NAPI_FUNCTION("isIncognitoMode", NapiWebviewController::IsIncognitoMode),
498 DECLARE_NAPI_FUNCTION("setPrintBackground", NapiWebviewController::SetPrintBackground),
499 DECLARE_NAPI_FUNCTION("getPrintBackground", NapiWebviewController::GetPrintBackground),
500 DECLARE_NAPI_FUNCTION("setWebSchemeHandler", NapiWebviewController::SetWebSchemeHandler),
501 DECLARE_NAPI_FUNCTION("clearWebSchemeHandler", NapiWebviewController::ClearWebSchemeHandler),
502 DECLARE_NAPI_FUNCTION("enableIntelligentTrackingPrevention",
503 NapiWebviewController::EnableIntelligentTrackingPrevention),
504 DECLARE_NAPI_FUNCTION("isIntelligentTrackingPreventionEnabled",
505 NapiWebviewController::IsIntelligentTrackingPreventionEnabled),
506 DECLARE_NAPI_STATIC_FUNCTION("addIntelligentTrackingPreventionBypassingList",
507 NapiWebviewController::AddIntelligentTrackingPreventionBypassingList),
508 DECLARE_NAPI_STATIC_FUNCTION("removeIntelligentTrackingPreventionBypassingList",
509 NapiWebviewController::RemoveIntelligentTrackingPreventionBypassingList),
510 DECLARE_NAPI_STATIC_FUNCTION("clearIntelligentTrackingPreventionBypassingList",
511 NapiWebviewController::ClearIntelligentTrackingPreventionBypassingList),
512 DECLARE_NAPI_FUNCTION("getLastJavascriptProxyCallingFrameUrl",
513 NapiWebviewController::GetLastJavascriptProxyCallingFrameUrl),
514 DECLARE_NAPI_STATIC_FUNCTION("pauseAllTimers", NapiWebviewController::PauseAllTimers),
515 DECLARE_NAPI_STATIC_FUNCTION("resumeAllTimers", NapiWebviewController::ResumeAllTimers),
516 DECLARE_NAPI_FUNCTION("startCamera", NapiWebviewController::StartCamera),
517 DECLARE_NAPI_FUNCTION("stopCamera", NapiWebviewController::StopCamera),
518 DECLARE_NAPI_FUNCTION("closeCamera", NapiWebviewController::CloseCamera),
519 DECLARE_NAPI_FUNCTION("closeAllMediaPresentations", NapiWebviewController::CloseAllMediaPresentations),
520 DECLARE_NAPI_FUNCTION("stopAllMedia", NapiWebviewController::StopAllMedia),
521 DECLARE_NAPI_FUNCTION("resumeAllMedia", NapiWebviewController::ResumeAllMedia),
522 DECLARE_NAPI_FUNCTION("pauseAllMedia", NapiWebviewController::PauseAllMedia),
523 DECLARE_NAPI_FUNCTION("getMediaPlaybackState", NapiWebviewController::GetMediaPlaybackState),
524 DECLARE_NAPI_FUNCTION("onCreateNativeMediaPlayer", NapiWebviewController::OnCreateNativeMediaPlayer),
525 DECLARE_NAPI_STATIC_FUNCTION("prefetchResource", NapiWebviewController::PrefetchResource),
526 DECLARE_NAPI_STATIC_FUNCTION("clearPrefetchedResource", NapiWebviewController::ClearPrefetchedResource),
527 DECLARE_NAPI_STATIC_FUNCTION("setRenderProcessMode", NapiWebviewController::SetRenderProcessMode),
528 DECLARE_NAPI_STATIC_FUNCTION("getRenderProcessMode", NapiWebviewController::GetRenderProcessMode),
529 DECLARE_NAPI_FUNCTION("precompileJavaScript", NapiWebviewController::PrecompileJavaScript),
530 DECLARE_NAPI_FUNCTION("injectOfflineResources", NapiWebviewController::InjectOfflineResources),
531 DECLARE_NAPI_STATIC_FUNCTION("setHostIP", NapiWebviewController::SetHostIP),
532 DECLARE_NAPI_STATIC_FUNCTION("clearHostIP", NapiWebviewController::ClearHostIP),
533 DECLARE_NAPI_STATIC_FUNCTION("warmupServiceWorker", NapiWebviewController::WarmupServiceWorker),
534 DECLARE_NAPI_FUNCTION("getSurfaceId", NapiWebviewController::GetSurfaceId),
535 DECLARE_NAPI_STATIC_FUNCTION("enableWholeWebPageDrawing", NapiWebviewController::EnableWholeWebPageDrawing),
536 DECLARE_NAPI_FUNCTION("enableAdsBlock", NapiWebviewController::EnableAdsBlock),
537 DECLARE_NAPI_FUNCTION("isAdsBlockEnabled", NapiWebviewController::IsAdsBlockEnabled),
538 DECLARE_NAPI_FUNCTION("isAdsBlockEnabledForCurPage", NapiWebviewController::IsAdsBlockEnabledForCurPage),
539 DECLARE_NAPI_FUNCTION("webPageSnapshot", NapiWebviewController::WebPageSnapshot),
540 DECLARE_NAPI_FUNCTION("setUrlTrustList", NapiWebviewController::SetUrlTrustList),
541 DECLARE_NAPI_FUNCTION("setPathAllowingUniversalAccess",
542 NapiWebviewController::SetPathAllowingUniversalAccess),
543 DECLARE_NAPI_STATIC_FUNCTION("enableBackForwardCache", NapiWebviewController::EnableBackForwardCache),
544 DECLARE_NAPI_FUNCTION("setBackForwardCacheOptions", NapiWebviewController::SetBackForwardCacheOptions),
545 DECLARE_NAPI_FUNCTION("scrollByWithResult", NapiWebviewController::ScrollByWithResult),
546 DECLARE_NAPI_FUNCTION("updateInstanceId", NapiWebviewController::UpdateInstanceId),
547 DECLARE_NAPI_FUNCTION("getScrollOffset",
548 NapiWebviewController::GetScrollOffset),
549 };
550 napi_value constructor = nullptr;
551 napi_define_class(env, WEBVIEW_CONTROLLER_CLASS_NAME.c_str(), WEBVIEW_CONTROLLER_CLASS_NAME.length(),
552 NapiWebviewController::JsConstructor, nullptr, sizeof(properties) / sizeof(properties[0]),
553 properties, &constructor);
554 NAPI_ASSERT(env, constructor != nullptr, "define js class WebviewController failed");
555 napi_status status = napi_set_named_property(env, exports, "WebviewController", constructor);
556 NAPI_ASSERT(env, status == napi_ok, "set property WebviewController failed");
557
558 napi_value webMsgTypeEnum = nullptr;
559 napi_property_descriptor webMsgTypeProperties[] = {
560 DECLARE_NAPI_STATIC_PROPERTY("NOT_SUPPORT", NapiParseUtils::ToInt32Value(env,
561 static_cast<int32_t>(WebMessageType::NOTSUPPORT))),
562 DECLARE_NAPI_STATIC_PROPERTY("STRING", NapiParseUtils::ToInt32Value(env,
563 static_cast<int32_t>(WebMessageType::STRING))),
564 DECLARE_NAPI_STATIC_PROPERTY("NUMBER", NapiParseUtils::ToInt32Value(env,
565 static_cast<int32_t>(WebMessageType::NUMBER))),
566 DECLARE_NAPI_STATIC_PROPERTY("BOOLEAN", NapiParseUtils::ToInt32Value(env,
567 static_cast<int32_t>(WebMessageType::BOOLEAN))),
568 DECLARE_NAPI_STATIC_PROPERTY("ARRAY_BUFFER", NapiParseUtils::ToInt32Value(env,
569 static_cast<int32_t>(WebMessageType::ARRAYBUFFER))),
570 DECLARE_NAPI_STATIC_PROPERTY("ARRAY", NapiParseUtils::ToInt32Value(env,
571 static_cast<int32_t>(WebMessageType::ARRAY))),
572 DECLARE_NAPI_STATIC_PROPERTY("ERROR", NapiParseUtils::ToInt32Value(env,
573 static_cast<int32_t>(WebMessageType::ERROR)))
574 };
575 napi_define_class(env, WEB_PORT_MSG_ENUM_NAME.c_str(), WEB_PORT_MSG_ENUM_NAME.length(),
576 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(webMsgTypeProperties) /
577 sizeof(webMsgTypeProperties[0]), webMsgTypeProperties, &webMsgTypeEnum);
578 napi_set_named_property(env, exports, WEB_PORT_MSG_ENUM_NAME.c_str(), webMsgTypeEnum);
579
580 napi_value webMsgExtClass = nullptr;
581 napi_property_descriptor webMsgExtClsProperties[] = {
582 DECLARE_NAPI_FUNCTION("getType", NapiWebMessageExt::GetType),
583 DECLARE_NAPI_FUNCTION("getString", NapiWebMessageExt::GetString),
584 DECLARE_NAPI_FUNCTION("getNumber", NapiWebMessageExt::GetNumber),
585 DECLARE_NAPI_FUNCTION("getBoolean", NapiWebMessageExt::GetBoolean),
586 DECLARE_NAPI_FUNCTION("getArrayBuffer", NapiWebMessageExt::GetArrayBuffer),
587 DECLARE_NAPI_FUNCTION("getArray", NapiWebMessageExt::GetArray),
588 DECLARE_NAPI_FUNCTION("getError", NapiWebMessageExt::GetError),
589 DECLARE_NAPI_FUNCTION("setType", NapiWebMessageExt::SetType),
590 DECLARE_NAPI_FUNCTION("setString", NapiWebMessageExt::SetString),
591 DECLARE_NAPI_FUNCTION("setNumber", NapiWebMessageExt::SetNumber),
592 DECLARE_NAPI_FUNCTION("setBoolean", NapiWebMessageExt::SetBoolean),
593 DECLARE_NAPI_FUNCTION("setArrayBuffer", NapiWebMessageExt::SetArrayBuffer),
594 DECLARE_NAPI_FUNCTION("setArray", NapiWebMessageExt::SetArray),
595 DECLARE_NAPI_FUNCTION("setError", NapiWebMessageExt::SetError)
596 };
597 napi_define_class(env, WEB_EXT_MSG_CLASS_NAME.c_str(), WEB_EXT_MSG_CLASS_NAME.length(),
598 NapiWebMessageExt::JsConstructor, nullptr, sizeof(webMsgExtClsProperties) / sizeof(webMsgExtClsProperties[0]),
599 webMsgExtClsProperties, &webMsgExtClass);
600 napi_create_reference(env, webMsgExtClass, 1, &g_webMsgExtClassRef);
601 napi_set_named_property(env, exports, WEB_EXT_MSG_CLASS_NAME.c_str(), webMsgExtClass);
602
603 napi_value securityLevelEnum = nullptr;
604 napi_property_descriptor securityLevelProperties[] = {
605 DECLARE_NAPI_STATIC_PROPERTY("NONE", NapiParseUtils::ToInt32Value(env,
606 static_cast<int32_t>(SecurityLevel::NONE))),
607 DECLARE_NAPI_STATIC_PROPERTY("SECURE", NapiParseUtils::ToInt32Value(env,
608 static_cast<int32_t>(SecurityLevel::SECURE))),
609 DECLARE_NAPI_STATIC_PROPERTY("WARNING", NapiParseUtils::ToInt32Value(env,
610 static_cast<int32_t>(SecurityLevel::WARNING))),
611 DECLARE_NAPI_STATIC_PROPERTY("DANGEROUS", NapiParseUtils::ToInt32Value(env,
612 static_cast<int32_t>(SecurityLevel::DANGEROUS)))
613 };
614 napi_define_class(env, WEB_SECURITY_LEVEL_ENUM_NAME.c_str(), WEB_SECURITY_LEVEL_ENUM_NAME.length(),
615 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(securityLevelProperties) /
616 sizeof(securityLevelProperties[0]), securityLevelProperties, &securityLevelEnum);
617 napi_set_named_property(env, exports, WEB_SECURITY_LEVEL_ENUM_NAME.c_str(), securityLevelEnum);
618
619 napi_value msgPortCons = nullptr;
620 napi_property_descriptor msgPortProperties[] = {
621 DECLARE_NAPI_FUNCTION("close", NapiWebMessagePort::Close),
622 DECLARE_NAPI_FUNCTION("postMessageEvent", NapiWebMessagePort::PostMessageEvent),
623 DECLARE_NAPI_FUNCTION("onMessageEvent", NapiWebMessagePort::OnMessageEvent),
624 DECLARE_NAPI_FUNCTION("postMessageEventExt", NapiWebMessagePort::PostMessageEventExt),
625 DECLARE_NAPI_FUNCTION("onMessageEventExt", NapiWebMessagePort::OnMessageEventExt)
626 };
627 NAPI_CALL(env, napi_define_class(env, WEB_MESSAGE_PORT_CLASS_NAME.c_str(), WEB_MESSAGE_PORT_CLASS_NAME.length(),
628 NapiWebMessagePort::JsConstructor, nullptr, sizeof(msgPortProperties) / sizeof(msgPortProperties[0]),
629 msgPortProperties, &msgPortCons));
630 NAPI_CALL(env, napi_create_reference(env, msgPortCons, 1, &g_classWebMsgPort));
631 NAPI_CALL(env, napi_set_named_property(env, exports, WEB_MESSAGE_PORT_CLASS_NAME.c_str(), msgPortCons));
632
633 napi_value hitTestTypeEnum = nullptr;
634 napi_property_descriptor hitTestTypeProperties[] = {
635 DECLARE_NAPI_STATIC_PROPERTY("EditText", NapiParseUtils::ToInt32Value(env,
636 static_cast<int32_t>(WebHitTestType::EDIT))),
637 DECLARE_NAPI_STATIC_PROPERTY("Email", NapiParseUtils::ToInt32Value(env,
638 static_cast<int32_t>(WebHitTestType::EMAIL))),
639 DECLARE_NAPI_STATIC_PROPERTY("HttpAnchor", NapiParseUtils::ToInt32Value(env,
640 static_cast<int32_t>(WebHitTestType::HTTP))),
641 DECLARE_NAPI_STATIC_PROPERTY("HttpAnchorImg", NapiParseUtils::ToInt32Value(env,
642 static_cast<int32_t>(WebHitTestType::HTTP_IMG))),
643 DECLARE_NAPI_STATIC_PROPERTY("Img", NapiParseUtils::ToInt32Value(env,
644 static_cast<int32_t>(WebHitTestType::IMG))),
645 DECLARE_NAPI_STATIC_PROPERTY("Map", NapiParseUtils::ToInt32Value(env,
646 static_cast<int32_t>(WebHitTestType::MAP))),
647 DECLARE_NAPI_STATIC_PROPERTY("Phone", NapiParseUtils::ToInt32Value(env,
648 static_cast<int32_t>(WebHitTestType::PHONE))),
649 DECLARE_NAPI_STATIC_PROPERTY("Unknown", NapiParseUtils::ToInt32Value(env,
650 static_cast<int32_t>(WebHitTestType::UNKNOWN))),
651 };
652 napi_define_class(env, WEB_HITTESTTYPE_V9_ENUM_NAME.c_str(), WEB_HITTESTTYPE_V9_ENUM_NAME.length(),
653 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(hitTestTypeProperties) /
654 sizeof(hitTestTypeProperties[0]), hitTestTypeProperties, &hitTestTypeEnum);
655 napi_set_named_property(env, exports, WEB_HITTESTTYPE_V9_ENUM_NAME.c_str(), hitTestTypeEnum);
656
657 napi_define_class(env, WEB_HITTESTTYPE_ENUM_NAME.c_str(), WEB_HITTESTTYPE_ENUM_NAME.length(),
658 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(hitTestTypeProperties) /
659 sizeof(hitTestTypeProperties[0]), hitTestTypeProperties, &hitTestTypeEnum);
660 napi_set_named_property(env, exports, WEB_HITTESTTYPE_ENUM_NAME.c_str(), hitTestTypeEnum);
661
662 napi_value secureDnsModeEnum = nullptr;
663 napi_property_descriptor secureDnsModeProperties[] = {
664 DECLARE_NAPI_STATIC_PROPERTY("Off", NapiParseUtils::ToInt32Value(env,
665 static_cast<int32_t>(SecureDnsModeType::OFF))),
666 DECLARE_NAPI_STATIC_PROPERTY("Auto", NapiParseUtils::ToInt32Value(env,
667 static_cast<int32_t>(SecureDnsModeType::AUTO))),
668 DECLARE_NAPI_STATIC_PROPERTY("SecureOnly", NapiParseUtils::ToInt32Value(env,
669 static_cast<int32_t>(SecureDnsModeType::SECURE_ONLY))),
670 DECLARE_NAPI_STATIC_PROPERTY("OFF", NapiParseUtils::ToInt32Value(env,
671 static_cast<int32_t>(SecureDnsModeType::OFF))),
672 DECLARE_NAPI_STATIC_PROPERTY("AUTO", NapiParseUtils::ToInt32Value(env,
673 static_cast<int32_t>(SecureDnsModeType::AUTO))),
674 DECLARE_NAPI_STATIC_PROPERTY("SECURE_ONLY", NapiParseUtils::ToInt32Value(env,
675 static_cast<int32_t>(SecureDnsModeType::SECURE_ONLY))),
676 };
677 napi_define_class(env, WEB_SECURE_DNS_MODE_ENUM_NAME.c_str(), WEB_SECURE_DNS_MODE_ENUM_NAME.length(),
678 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(secureDnsModeProperties) /
679 sizeof(secureDnsModeProperties[0]), secureDnsModeProperties, &secureDnsModeEnum);
680 napi_set_named_property(env, exports, WEB_SECURE_DNS_MODE_ENUM_NAME.c_str(), secureDnsModeEnum);
681
682 napi_value historyList = nullptr;
683 napi_property_descriptor historyListProperties[] = {
684 DECLARE_NAPI_FUNCTION("getItemAtIndex", NapiWebHistoryList::GetItem)
685 };
686 napi_define_class(env, WEB_HISTORY_LIST_CLASS_NAME.c_str(), WEB_HISTORY_LIST_CLASS_NAME.length(),
687 NapiWebHistoryList::JsConstructor, nullptr, sizeof(historyListProperties) / sizeof(historyListProperties[0]),
688 historyListProperties, &historyList);
689 napi_create_reference(env, historyList, 1, &g_historyListRef);
690 napi_set_named_property(env, exports, WEB_HISTORY_LIST_CLASS_NAME.c_str(), historyList);
691
692 napi_value webPrintDoc = nullptr;
693 napi_property_descriptor WebPrintDocumentClass[] = {
694 DECLARE_NAPI_FUNCTION("onStartLayoutWrite", NapiWebPrintDocument::OnStartLayoutWrite),
695 DECLARE_NAPI_FUNCTION("onJobStateChanged", NapiWebPrintDocument::OnJobStateChanged),
696 };
697 napi_define_class(env, WEB_PRINT_DOCUMENT_CLASS_NAME.c_str(), WEB_PRINT_DOCUMENT_CLASS_NAME.length(),
698 NapiWebPrintDocument::JsConstructor, nullptr,
699 sizeof(WebPrintDocumentClass) / sizeof(WebPrintDocumentClass[0]),
700 WebPrintDocumentClass, &webPrintDoc);
701 napi_create_reference(env, webPrintDoc, 1, &g_webPrintDocClassRef);
702 napi_set_named_property(env, exports, WEB_PRINT_DOCUMENT_CLASS_NAME.c_str(), webPrintDoc);
703
704 napi_value renderProcessModeEnum = nullptr;
705 napi_property_descriptor renderProcessModeProperties[] = {
706 DECLARE_NAPI_STATIC_PROPERTY("SINGLE", NapiParseUtils::ToInt32Value(env,
707 static_cast<int32_t>(RenderProcessMode::SINGLE_MODE))),
708 DECLARE_NAPI_STATIC_PROPERTY("MULTIPLE", NapiParseUtils::ToInt32Value(env,
709 static_cast<int32_t>(RenderProcessMode::MULTIPLE_MODE))),
710 };
711 napi_define_class(env, WEB_RENDER_PROCESS_MODE_ENUM_NAME.c_str(), WEB_RENDER_PROCESS_MODE_ENUM_NAME.length(),
712 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(renderProcessModeProperties) /
713 sizeof(renderProcessModeProperties[0]), renderProcessModeProperties, &renderProcessModeEnum);
714 napi_set_named_property(env, exports, WEB_RENDER_PROCESS_MODE_ENUM_NAME.c_str(), renderProcessModeEnum);
715
716 napi_value offlineResourceTypeEnum = nullptr;
717 napi_property_descriptor offlineResourceTypeProperties[] = {
718 DECLARE_NAPI_STATIC_PROPERTY("IMAGE", NapiParseUtils::ToInt32Value(env,
719 static_cast<int32_t>(OfflineResourceType::IMAGE))),
720 DECLARE_NAPI_STATIC_PROPERTY("CSS", NapiParseUtils::ToInt32Value(env,
721 static_cast<int32_t>(OfflineResourceType::CSS))),
722 DECLARE_NAPI_STATIC_PROPERTY("CLASSIC_JS", NapiParseUtils::ToInt32Value(env,
723 static_cast<int32_t>(OfflineResourceType::CLASSIC_JS))),
724 DECLARE_NAPI_STATIC_PROPERTY("MODULE_JS", NapiParseUtils::ToInt32Value(env,
725 static_cast<int32_t>(OfflineResourceType::MODULE_JS))),
726 };
727 napi_define_class(env, OFFLINE_RESOURCE_TYPE_ENUM_NAME.c_str(), OFFLINE_RESOURCE_TYPE_ENUM_NAME.length(),
728 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(offlineResourceTypeProperties) /
729 sizeof(offlineResourceTypeProperties[0]), offlineResourceTypeProperties, &offlineResourceTypeEnum);
730 napi_set_named_property(env, exports, OFFLINE_RESOURCE_TYPE_ENUM_NAME.c_str(), offlineResourceTypeEnum);
731
732 napi_value scrollTypeEnum = nullptr;
733 napi_property_descriptor scrollTypeProperties[] = {
734 DECLARE_NAPI_STATIC_PROPERTY("EVENT", NapiParseUtils::ToInt32Value(env,
735 static_cast<int32_t>(ScrollType::EVENT))),
736 };
737 napi_define_class(env, WEB_SCROLL_TYPE_ENUM_NAME.c_str(), WEB_SCROLL_TYPE_ENUM_NAME.length(),
738 NapiParseUtils::CreateEnumConstructor, nullptr, sizeof(scrollTypeProperties) /
739 sizeof(scrollTypeProperties[0]), scrollTypeProperties, &scrollTypeEnum);
740 napi_set_named_property(env, exports, WEB_SCROLL_TYPE_ENUM_NAME.c_str(), scrollTypeEnum);
741
742 WebviewJavaScriptExecuteCallback::InitJSExcute(env, exports);
743 return exports;
744 }
745
JsConstructor(napi_env env,napi_callback_info info)746 napi_value NapiWebviewController::JsConstructor(napi_env env, napi_callback_info info)
747 {
748 WVLOG_I("NapiWebviewController::JsConstructor start");
749 napi_value thisVar = nullptr;
750
751 size_t argc = INTEGER_ONE;
752 napi_value argv[INTEGER_ONE] = { 0 };
753 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
754
755 WebviewController *webviewController;
756 std::string webTag;
757 if (argc == 1) {
758 NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], webTag);
759 if (webTag.empty()) {
760 WVLOG_E("native webTag is empty");
761 return nullptr;
762 }
763 webviewController = new (std::nothrow) WebviewController(webTag);
764 WVLOG_I("new webview controller webname:%{public}s", webTag.c_str());
765 } else {
766 webTag = WebviewController::GenerateWebTag();
767 webviewController = new (std::nothrow) WebviewController(webTag);
768 }
769 WebviewController::webTagSet_.insert(webTag);
770
771 if (webviewController == nullptr) {
772 WVLOG_E("new webview controller failed");
773 return nullptr;
774 }
775 napi_status status = napi_wrap(
776 env, thisVar, webviewController,
777 [](napi_env env, void *data, void *hint) {
778 WebviewController *webviewController = static_cast<WebviewController *>(data);
779 delete webviewController;
780 },
781 nullptr, nullptr);
782 if (status != napi_ok) {
783 WVLOG_E("Wrap native webviewController failed.");
784 delete webviewController;
785 webviewController = nullptr;
786 return nullptr;
787 }
788 return thisVar;
789 }
790
InitializeWebEngine(napi_env env,napi_callback_info info)791 napi_value NapiWebviewController::InitializeWebEngine(napi_env env, napi_callback_info info)
792 {
793 WVLOG_D("InitializeWebEngine invoked.");
794
795 // obtain bundle path
796 std::shared_ptr<AbilityRuntime::ApplicationContext> ctx =
797 AbilityRuntime::ApplicationContext::GetApplicationContext();
798 if (!ctx) {
799 WVLOG_E("Failed to init web engine due to nil application context.");
800 return nullptr;
801 }
802
803 // load so
804 const std::string& bundlePath = ctx->GetBundleCodeDir();
805 NWebHelper::Instance().SetBundlePath(bundlePath);
806 if (!NWebHelper::Instance().InitAndRun(true)) {
807 WVLOG_E("Failed to init web engine due to NWebHelper failure.");
808 return nullptr;
809 }
810
811 napi_value result = nullptr;
812 NAPI_CALL(env, napi_get_undefined(env, &result));
813 WVLOG_I("NWebHelper initialized, init web engine done, bundle_path: %{public}s", bundlePath.c_str());
814 return result;
815 }
816
SetHttpDns(napi_env env,napi_callback_info info)817 napi_value NapiWebviewController::SetHttpDns(napi_env env, napi_callback_info info)
818 {
819 napi_value thisVar = nullptr;
820 napi_value result = nullptr;
821 size_t argc = INTEGER_TWO;
822 napi_value argv[INTEGER_TWO] = { 0 };
823 int dohMode;
824 std::string dohConfig;
825
826 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
827 if (argc != INTEGER_TWO) {
828 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
829 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
830 return result;
831 }
832
833 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], dohMode)) {
834 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
835 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "secureDnsMode", "SecureDnsMode"));
836 return result;
837 }
838
839 if (dohMode < static_cast<int>(SecureDnsModeType::OFF) ||
840 dohMode > static_cast<int>(SecureDnsModeType::SECURE_ONLY)) {
841 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
842 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "secureDnsMode"));
843 return result;
844 }
845
846 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ONE], dohConfig)) {
847 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
848 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "secureDnsConfig", "string"));
849 return result;
850 }
851
852 if (dohConfig.rfind("https", 0) != 0 && dohConfig.rfind("HTTPS", 0) != 0) {
853 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
854 "BusinessError 401: Parameter error. Parameter secureDnsConfig must start with 'http' or 'https'.");
855 return result;
856 }
857
858 std::shared_ptr<NWebDOHConfigImpl> config = std::make_shared<NWebDOHConfigImpl>();
859 config->SetMode(dohMode);
860 config->SetConfig(dohConfig);
861 WVLOG_I("set http dns mode:%{public}d doh_config:%{public}s", dohMode, dohConfig.c_str());
862
863 NWebHelper::Instance().SetHttpDns(config);
864
865 NAPI_CALL(env, napi_get_undefined(env, &result));
866 return result;
867 }
868
SetWebDebuggingAccess(napi_env env,napi_callback_info info)869 napi_value NapiWebviewController::SetWebDebuggingAccess(napi_env env, napi_callback_info info)
870 {
871 WVLOG_D("SetWebDebuggingAccess start");
872 napi_value result = nullptr;
873 if (OHOS::system::GetBoolParameter("web.debug.devtools", false)) {
874 return result;
875 }
876 napi_value thisVar = nullptr;
877 size_t argc = INTEGER_ONE;
878 napi_value argv[INTEGER_ONE] = {0};
879
880 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
881 if (argc != INTEGER_ONE) {
882 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
883 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
884 return result;
885 }
886
887 bool webDebuggingAccess = false;
888 if (!NapiParseUtils::ParseBoolean(env, argv[0], webDebuggingAccess)) {
889 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
890 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "webDebuggingAccess", "boolean"));
891 return result;
892 }
893 WebviewController::webDebuggingAccess_ = webDebuggingAccess;
894
895 NAPI_CALL(env, napi_get_undefined(env, &result));
896 return result;
897 }
898
EnableSafeBrowsing(napi_env env,napi_callback_info info)899 napi_value NapiWebviewController::EnableSafeBrowsing(napi_env env, napi_callback_info info)
900 {
901 WVLOG_D("EnableSafeBrowsing start");
902 napi_value result = nullptr;
903 napi_value thisVar = nullptr;
904 size_t argc = INTEGER_ONE;
905 napi_value argv[INTEGER_ONE] = {0};
906
907 NAPI_CALL(env, napi_get_undefined(env, &result));
908 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
909 if (argc != INTEGER_ONE) {
910 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
911 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
912 return result;
913 }
914
915 bool safeBrowsingEnable = false;
916 if (!NapiParseUtils::ParseBoolean(env, argv[0], safeBrowsingEnable)) {
917 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
918 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "enable", "boolean"));
919 return result;
920 }
921
922 WebviewController *controller = nullptr;
923 napi_unwrap(env, thisVar, (void **)&controller);
924 if (!controller || !controller->IsInit()) {
925 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
926 return result;
927 }
928 controller->EnableSafeBrowsing(safeBrowsingEnable);
929 return result;
930 }
931
IsSafeBrowsingEnabled(napi_env env,napi_callback_info info)932 napi_value NapiWebviewController::IsSafeBrowsingEnabled(napi_env env, napi_callback_info info)
933 {
934 WVLOG_D("IsSafeBrowsingEnabled start");
935 napi_value result = nullptr;
936 WebviewController *webviewController = GetWebviewController(env, info);
937 if (!webviewController) {
938 return nullptr;
939 }
940
941 bool isSafeBrowsingEnabled = webviewController->IsSafeBrowsingEnabled();
942 NAPI_CALL(env, napi_get_boolean(env, isSafeBrowsingEnabled, &result));
943 return result;
944 }
945
InnerGetWebDebuggingAccess(napi_env env,napi_callback_info info)946 napi_value NapiWebviewController::InnerGetWebDebuggingAccess(napi_env env, napi_callback_info info)
947 {
948 WVLOG_D("InnerGetWebDebuggingAccess start");
949 bool webDebuggingAccess = WebviewController::webDebuggingAccess_;
950 napi_value result = nullptr;
951 napi_get_boolean(env, webDebuggingAccess, &result);
952 return result;
953 }
954
InnerGetThisVar(napi_env env,napi_callback_info info)955 napi_value NapiWebviewController::InnerGetThisVar(napi_env env, napi_callback_info info)
956 {
957 WVLOG_D("InnerGetThisVar start");
958 napi_value thisVar = nullptr;
959 napi_value result = nullptr;
960 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
961 WebviewController *webviewController = nullptr;
962 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
963 if ((!webviewController) || (status != napi_ok)) {
964 WVLOG_E("webviewController is nullptr.");
965 napi_create_int64(env, 0, &result);
966 } else {
967 napi_create_int64(env, reinterpret_cast<int64_t>(webviewController), &result);
968 }
969 return result;
970 }
971
SetWebId(napi_env env,napi_callback_info info)972 napi_value NapiWebviewController::SetWebId(napi_env env, napi_callback_info info)
973 {
974 napi_value thisVar = nullptr;
975 size_t argc = INTEGER_ONE;
976 napi_value argv[INTEGER_ONE];
977 void* data = nullptr;
978 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
979
980 int32_t webId = -1;
981 if (!NapiParseUtils::ParseInt32(env, argv[0], webId)) {
982 WVLOG_E("Parse web id failed.");
983 return nullptr;
984 }
985 WebviewController *webviewController = nullptr;
986 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
987 if ((!webviewController) || (status != napi_ok)) {
988 WVLOG_E("webviewController is nullptr.");
989 return nullptr;
990 }
991 webviewController->SetWebId(webId);
992 return thisVar;
993 }
994
InnerSetHapPath(napi_env env,napi_callback_info info)995 napi_value NapiWebviewController::InnerSetHapPath(napi_env env, napi_callback_info info)
996 {
997 napi_value result = nullptr;
998 NAPI_CALL(env, napi_get_undefined(env, &result));
999 napi_value thisVar = nullptr;
1000 size_t argc = INTEGER_ONE;
1001 napi_value argv[INTEGER_ONE];
1002 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1003 if (argc != INTEGER_ONE) {
1004 WVLOG_E("Failed to run InnerSetHapPath beacuse of wrong Param number.");
1005 return result;
1006 }
1007 std::string hapPath;
1008 if (!NapiParseUtils::ParseString(env, argv[0], hapPath)) {
1009 WVLOG_E("Parse hap path failed.");
1010 return result;
1011 }
1012 WebviewController *webviewController = nullptr;
1013 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
1014 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
1015 WVLOG_E("Wrap webviewController failed. WebviewController must be associated with a Web component.");
1016 return result;
1017 }
1018 webviewController->InnerSetHapPath(hapPath);
1019 return result;
1020 }
1021
InnerJsProxy(napi_env env,napi_callback_info info)1022 napi_value NapiWebviewController::InnerJsProxy(napi_env env, napi_callback_info info)
1023 {
1024 napi_value thisVar = nullptr;
1025 napi_value result = nullptr;
1026 size_t argc = INTEGER_FIVE;
1027 napi_value argv[INTEGER_FIVE] = { 0 };
1028 napi_get_undefined(env, &result);
1029 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1030 if (argc != INTEGER_FIVE) {
1031 WVLOG_E("Failed to run InnerJsProxy beacuse of wrong Param number.");
1032 return result;
1033 }
1034 napi_valuetype valueType = napi_undefined;
1035 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
1036 if (valueType != napi_object) {
1037 WVLOG_E("Failed to run InnerJsProxy beacuse of wrong Param type.");
1038 return result;
1039 }
1040 std::string objName;
1041 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ONE], objName)) {
1042 WVLOG_E("Failed to run InnerJsProxy beacuse of wrong object name.");
1043 return result;
1044 }
1045 std::vector<std::string> methodList;
1046 bool hasSyncMethod = NapiParseUtils::ParseStringArray(env, argv[INTEGER_TWO], methodList);
1047 std::vector<std::string> asyncMethodList;
1048 bool hasAsyncMethod = NapiParseUtils::ParseStringArray(env, argv[INTEGER_THREE], asyncMethodList);
1049 if (!hasSyncMethod && !hasAsyncMethod) {
1050 WVLOG_E("Failed to run InnerJsProxy beacuse of empty method lists.");
1051 return result;
1052 }
1053 std::string permission = "";
1054 NapiParseUtils::ParseString(env, argv[INTEGER_FOUR], permission);
1055 WebviewController* controller = nullptr;
1056 napi_unwrap(env, thisVar, (void **)&controller);
1057 if (!controller || !controller->IsInit()) {
1058 WVLOG_E("Failed to run InnerJsProxy. The WebviewController must be associted with a Web component.");
1059 return result;
1060 }
1061 controller->SetNWebJavaScriptResultCallBack();
1062 RegisterJavaScriptProxyParam param;
1063 param.env = env;
1064 param.obj = argv[INTEGER_ZERO];
1065 param.objName = objName;
1066 param.syncMethodList = methodList;
1067 param.asyncMethodList = asyncMethodList;
1068 param.permission = permission;
1069 controller->RegisterJavaScriptProxy(param);
1070 return result;
1071 }
1072
InnerGetCustomeSchemeCmdLine(napi_env env,napi_callback_info info)1073 napi_value NapiWebviewController::InnerGetCustomeSchemeCmdLine(napi_env env, napi_callback_info info)
1074 {
1075 WebviewController::existNweb_ = true;
1076 napi_value result = nullptr;
1077 const std::string& cmdLine = WebviewController::customeSchemeCmdLine_;
1078 napi_create_string_utf8(env, cmdLine.c_str(), cmdLine.length(), &result);
1079 return result;
1080 }
1081
AccessForward(napi_env env,napi_callback_info info)1082 napi_value NapiWebviewController::AccessForward(napi_env env, napi_callback_info info)
1083 {
1084 napi_value result = nullptr;
1085 WebviewController *webviewController = GetWebviewController(env, info);
1086 if (!webviewController) {
1087 return nullptr;
1088 }
1089
1090 bool access = webviewController->AccessForward();
1091 NAPI_CALL(env, napi_get_boolean(env, access, &result));
1092 return result;
1093 }
1094
AccessBackward(napi_env env,napi_callback_info info)1095 napi_value NapiWebviewController::AccessBackward(napi_env env, napi_callback_info info)
1096 {
1097 napi_value result = nullptr;
1098 WebviewController *webviewController = GetWebviewController(env, info);
1099 if (!webviewController) {
1100 return nullptr;
1101 }
1102
1103 bool access = webviewController->AccessBackward();
1104 NAPI_CALL(env, napi_get_boolean(env, access, &result));
1105 return result;
1106 }
1107
Forward(napi_env env,napi_callback_info info)1108 napi_value NapiWebviewController::Forward(napi_env env, napi_callback_info info)
1109 {
1110 napi_value result = nullptr;
1111 WebviewController *webviewController = GetWebviewController(env, info);
1112 if (!webviewController) {
1113 return nullptr;
1114 }
1115
1116 webviewController->Forward();
1117 NAPI_CALL(env, napi_get_undefined(env, &result));
1118 return result;
1119 }
1120
Backward(napi_env env,napi_callback_info info)1121 napi_value NapiWebviewController::Backward(napi_env env, napi_callback_info info)
1122 {
1123 napi_value result = nullptr;
1124 WebviewController *webviewController = GetWebviewController(env, info);
1125 if (!webviewController) {
1126 return nullptr;
1127 }
1128
1129 webviewController->Backward();
1130 NAPI_CALL(env, napi_get_undefined(env, &result));
1131 return result;
1132 }
1133
AccessStep(napi_env env,napi_callback_info info)1134 napi_value NapiWebviewController::AccessStep(napi_env env, napi_callback_info info)
1135 {
1136 napi_value thisVar = nullptr;
1137 napi_value result = nullptr;
1138 size_t argc = INTEGER_ONE;
1139 napi_value argv[INTEGER_ONE];
1140 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1141 if (argc != INTEGER_ONE) {
1142 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1143 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1144 return nullptr;
1145 }
1146
1147 int32_t step = INTEGER_ZERO;
1148 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], step)) {
1149 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1150 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "step", "number"));
1151 return nullptr;
1152 }
1153
1154 WebviewController *webviewController = nullptr;
1155 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
1156 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
1157 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
1158 return nullptr;
1159 }
1160
1161 bool access = webviewController->AccessStep(step);
1162 NAPI_CALL(env, napi_get_boolean(env, access, &result));
1163 return result;
1164 }
1165
ClearHistory(napi_env env,napi_callback_info info)1166 napi_value NapiWebviewController::ClearHistory(napi_env env, napi_callback_info info)
1167 {
1168 napi_value result = nullptr;
1169 WebviewController *webviewController = GetWebviewController(env, info);
1170 if (!webviewController) {
1171 return nullptr;
1172 }
1173
1174 webviewController->ClearHistory();
1175 NAPI_CALL(env, napi_get_undefined(env, &result));
1176 return result;
1177 }
1178
OnActive(napi_env env,napi_callback_info info)1179 napi_value NapiWebviewController::OnActive(napi_env env, napi_callback_info info)
1180 {
1181 napi_value result = nullptr;
1182 WebviewController *webviewController = GetWebviewController(env, info);
1183 if (!webviewController) {
1184 WVLOG_E("NapiWebviewController::OnActive get controller failed");
1185 return nullptr;
1186 }
1187
1188 webviewController->OnActive();
1189 WVLOG_I("The web component has been successfully activated");
1190 NAPI_CALL(env, napi_get_undefined(env, &result));
1191 return result;
1192 }
1193
OnInactive(napi_env env,napi_callback_info info)1194 napi_value NapiWebviewController::OnInactive(napi_env env, napi_callback_info info)
1195 {
1196 napi_value result = nullptr;
1197 WebviewController *webviewController = GetWebviewController(env, info);
1198 if (!webviewController) {
1199 WVLOG_E("NapiWebviewController::OnInactive get controller failed");
1200 return nullptr;
1201 }
1202
1203 webviewController->OnInactive();
1204 WVLOG_I("The web component has been successfully inactivated");
1205 NAPI_CALL(env, napi_get_undefined(env, &result));
1206 return result;
1207 }
1208
Refresh(napi_env env,napi_callback_info info)1209 napi_value NapiWebviewController::Refresh(napi_env env, napi_callback_info info)
1210 {
1211 napi_value result = nullptr;
1212 WebviewController *webviewController = GetWebviewController(env, info);
1213 if (!webviewController) {
1214 return nullptr;
1215 }
1216
1217 webviewController->Refresh();
1218 NAPI_CALL(env, napi_get_undefined(env, &result));
1219 return result;
1220 }
1221
1222
JsConstructor(napi_env env,napi_callback_info info)1223 napi_value NapiWebMessageExt::JsConstructor(napi_env env, napi_callback_info info)
1224 {
1225 WVLOG_D("NapiWebMessageExt::JsConstructor");
1226 napi_value thisVar = nullptr;
1227 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
1228
1229 auto webMsg = std::make_shared<OHOS::NWeb::NWebMessage>(NWebValue::Type::NONE);
1230 WebMessageExt *webMessageExt = new (std::nothrow) WebMessageExt(webMsg);
1231 if (webMessageExt == nullptr) {
1232 WVLOG_E("new msg port failed");
1233 return nullptr;
1234 }
1235 NAPI_CALL(env, napi_wrap(env, thisVar, webMessageExt,
1236 [](napi_env env, void *data, void *hint) {
1237 WebMessageExt *webMessageExt = static_cast<WebMessageExt *>(data);
1238 if (webMessageExt) {
1239 delete webMessageExt;
1240 }
1241 },
1242 nullptr, nullptr));
1243 return thisVar;
1244 }
1245
GetType(napi_env env,napi_callback_info info)1246 napi_value NapiWebMessageExt::GetType(napi_env env, napi_callback_info info)
1247 {
1248 WVLOG_D("NapiWebMessageExt::GetType start");
1249 napi_value thisVar = nullptr;
1250 napi_value result = nullptr;
1251 napi_status status = napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
1252 if (status != napi_status::napi_ok) {
1253 WVLOG_E("napi_get_cb_info status not ok");
1254 return result;
1255 }
1256
1257 if (thisVar == nullptr) {
1258 WVLOG_E("napi_get_cb_info thisVar is nullptr");
1259 return result;
1260 }
1261
1262 WebMessageExt *webMessageExt = nullptr;
1263 status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1264 if ((!webMessageExt) || (status != napi_ok)) {
1265 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
1266 return nullptr;
1267 }
1268
1269 int32_t type = webMessageExt->GetType();
1270 status = napi_create_int32(env, type, &result);
1271 if (status != napi_status::napi_ok) {
1272 WVLOG_E("napi_create_int32 failed.");
1273 return result;
1274 }
1275 return result;
1276 }
1277
GetString(napi_env env,napi_callback_info info)1278 napi_value NapiWebMessageExt::GetString(napi_env env, napi_callback_info info)
1279 {
1280 WVLOG_D(" GetString webJsMessageExt start");
1281 napi_value thisVar = nullptr;
1282 napi_value result = nullptr;
1283 size_t argc = INTEGER_ONE;
1284 napi_value argv[INTEGER_ONE] = { 0 };
1285
1286 WebMessageExt *webJsMessageExt = nullptr;
1287 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1288 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1289 if (webJsMessageExt == nullptr) {
1290 WVLOG_E("unwrap webJsMessageExt failed.");
1291 return result;
1292 }
1293
1294 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::STRING)) {
1295 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1296 return nullptr;
1297 }
1298
1299 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1300 return result;
1301 }
1302
GetNumber(napi_env env,napi_callback_info info)1303 napi_value NapiWebMessageExt::GetNumber(napi_env env, napi_callback_info info)
1304 {
1305 WVLOG_D("GetNumber webJsMessageExt start");
1306 napi_value thisVar = nullptr;
1307 napi_value result = nullptr;
1308 size_t argc = INTEGER_ONE;
1309 napi_value argv[INTEGER_ONE] = { 0 };
1310
1311 WebMessageExt *webJsMessageExt = nullptr;
1312 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1313 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1314 if (webJsMessageExt == nullptr) {
1315 WVLOG_E("unwrap webJsMessageExt failed.");
1316 return result;
1317 }
1318
1319 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::NUMBER)) {
1320 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1321 WVLOG_E("GetNumber webJsMessageExt failed,not match");
1322 return nullptr;
1323 }
1324
1325 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1326 return result;
1327 }
1328
GetBoolean(napi_env env,napi_callback_info info)1329 napi_value NapiWebMessageExt::GetBoolean(napi_env env, napi_callback_info info)
1330 {
1331 napi_value thisVar = nullptr;
1332 napi_value result = nullptr;
1333 size_t argc = INTEGER_ONE;
1334 napi_value argv[INTEGER_ONE] = { 0 };
1335
1336 WebMessageExt *webJsMessageExt = nullptr;
1337 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1338 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1339 if (webJsMessageExt == nullptr) {
1340 WVLOG_E("unwrap webJsMessageExt failed.");
1341 return result;
1342 }
1343
1344 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::BOOLEAN)) {
1345 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1346 return nullptr;
1347 }
1348
1349 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1350 return result;
1351 }
1352
GetArrayBuffer(napi_env env,napi_callback_info info)1353 napi_value NapiWebMessageExt::GetArrayBuffer(napi_env env, napi_callback_info info)
1354 {
1355 napi_value thisVar = nullptr;
1356 napi_value result = nullptr;
1357 size_t argc = INTEGER_ONE;
1358 napi_value argv[INTEGER_ONE] = { 0 };
1359
1360 WebMessageExt *webJsMessageExt = nullptr;
1361 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1362 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1363 if (webJsMessageExt == nullptr) {
1364 WVLOG_E("unwrap webJsMessageExt failed.");
1365 return result;
1366 }
1367
1368 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::ARRAYBUFFER)) {
1369 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1370 return nullptr;
1371 }
1372 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1373 return result;
1374 }
1375
GetArray(napi_env env,napi_callback_info info)1376 napi_value NapiWebMessageExt::GetArray(napi_env env, napi_callback_info info)
1377 {
1378 napi_value thisVar = nullptr;
1379 napi_value result = nullptr;
1380 size_t argc = INTEGER_ONE;
1381 napi_value argv[INTEGER_ONE] = { 0 };
1382
1383 WebMessageExt *webJsMessageExt = nullptr;
1384 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1385 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1386 if (webJsMessageExt == nullptr) {
1387 WVLOG_E("unwrap webJsMessageExt failed.");
1388 return result;
1389 }
1390
1391 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::ARRAY)) {
1392 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1393 return nullptr;
1394 }
1395
1396 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1397 return result;
1398 }
1399
GetError(napi_env env,napi_callback_info info)1400 napi_value NapiWebMessageExt::GetError(napi_env env, napi_callback_info info)
1401 {
1402 napi_value thisVar = nullptr;
1403 napi_value result = nullptr;
1404 size_t argc = INTEGER_ONE;
1405 napi_value argv[INTEGER_ONE] = { 0 };
1406
1407 WebMessageExt *webJsMessageExt = nullptr;
1408 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1409 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webJsMessageExt));
1410 if (webJsMessageExt == nullptr) {
1411 WVLOG_E("unwrap webJsMessageExt failed.");
1412 return result;
1413 }
1414
1415 if (webJsMessageExt->GetType() != static_cast<int32_t>(WebMessageType::ERROR)) {
1416 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1417 return nullptr;
1418 }
1419
1420 NapiParseUtils::ConvertNWebToNapiValue(env, webJsMessageExt->GetData(), result);
1421 return result;
1422 }
1423
SetType(napi_env env,napi_callback_info info)1424 napi_value NapiWebMessageExt::SetType(napi_env env, napi_callback_info info)
1425 {
1426 WVLOG_D("NapiWebMessageExt::SetType");
1427 napi_value thisVar = nullptr;
1428 napi_value result = nullptr;
1429 size_t argc = INTEGER_ONE;
1430 napi_value argv[INTEGER_ONE] = { 0 };
1431 int type = -1;
1432 napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1433 if (status != napi_ok) {
1434 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1435 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "type"));
1436 WVLOG_E("NapiWebMessageExt::SetType napi_get_cb_info failed");
1437 return result;
1438 }
1439 if (thisVar == nullptr) {
1440 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1441 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NOT_NULL, "type"));
1442 WVLOG_E("NapiWebMessageExt::SetType thisVar is null");
1443 return result;
1444 }
1445 if (argc != INTEGER_ONE) {
1446 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1447 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1448 return result;
1449 }
1450 if (!NapiParseUtils::ParseInt32(env, argv[0], type)) {
1451 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, ParamCheckErrorMsgTemplate::TYPE_ALL_INT);
1452 return result;
1453 }
1454 if (type <= static_cast<int>(WebMessageType::NOTSUPPORT) || type > static_cast<int>(WebMessageType::ERROR)) {
1455 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1456 return result;
1457 }
1458 WebMessageExt *webMessageExt = nullptr;
1459 status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1460 if (status != napi_ok) {
1461 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1462 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "type"));
1463 WVLOG_E("NapiWebMessageExt::SetType napi_unwrap failed");
1464 return result;
1465 }
1466 if (!webMessageExt) {
1467 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1468 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NOT_NULL, "type"));
1469 WVLOG_E("NapiWebMessageExt::SetType webMessageExt is null");
1470 return result;
1471 }
1472 webMessageExt->SetType(type);
1473 return result;
1474 }
1475
SetString(napi_env env,napi_callback_info info)1476 napi_value NapiWebMessageExt::SetString(napi_env env, napi_callback_info info)
1477 {
1478 WVLOG_D("NapiWebMessageExt::SetString start");
1479 napi_value thisVar = nullptr;
1480 napi_value result = nullptr;
1481 size_t argc = INTEGER_ONE;
1482 napi_value argv[INTEGER_ONE] = { 0 };
1483 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1484 if (argc != INTEGER_ONE) {
1485 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1486 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1487 return result;
1488 }
1489
1490 std::string value;
1491 if (!NapiParseUtils::ParseString(env, argv[0], value)) {
1492 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1493 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "string"));
1494 return result;
1495 }
1496 WebMessageExt *webMessageExt = nullptr;
1497 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1498 if ((!webMessageExt) || (status != napi_ok)) {
1499 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1500 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1501 return result;
1502 }
1503
1504 int32_t type = webMessageExt->GetType();
1505 if (type != static_cast<int32_t>(WebMessageType::STRING)) {
1506 WVLOG_E("web message SetString error type:%{public}d", type);
1507 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1508 return result;
1509 }
1510 webMessageExt->SetString(value);
1511 return result;
1512 }
1513
SetNumber(napi_env env,napi_callback_info info)1514 napi_value NapiWebMessageExt::SetNumber(napi_env env, napi_callback_info info)
1515 {
1516 WVLOG_D("NapiWebMessageExt::SetNumber start");
1517 napi_value thisVar = nullptr;
1518 napi_value result = nullptr;
1519 size_t argc = INTEGER_ONE;
1520 napi_value argv[INTEGER_ONE] = { 0 };
1521 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1522 if (argc != INTEGER_ONE) {
1523 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1524 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1525 return result;
1526 }
1527
1528 double value = 0;
1529 if (!NapiParseUtils::ParseDouble(env, argv[0], value)) {
1530 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1531 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "number"));
1532 return result;
1533 }
1534
1535 WebMessageExt *webMessageExt = nullptr;
1536 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1537 if ((!webMessageExt) || (status != napi_ok)) {
1538 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1539 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1540 return result;
1541 }
1542
1543 int32_t type = webMessageExt->GetType();
1544 if (type != static_cast<int32_t>(WebMessageType::NUMBER)) {
1545 WVLOG_E("web message SetNumber error type:%{public}d", type);
1546 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1547 return result;
1548 }
1549 webMessageExt->SetNumber(value);
1550 return result;
1551 }
1552
SetBoolean(napi_env env,napi_callback_info info)1553 napi_value NapiWebMessageExt::SetBoolean(napi_env env, napi_callback_info info)
1554 {
1555 WVLOG_D("NapiWebMessageExt::SetBoolean start");
1556 napi_value thisVar = nullptr;
1557 napi_value result = nullptr;
1558 size_t argc = INTEGER_ONE;
1559 napi_value argv[INTEGER_ONE] = { 0 };
1560 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1561 if (argc != INTEGER_ONE) {
1562 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1563 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1564 return result;
1565 }
1566
1567 bool value = 0;
1568 if (!NapiParseUtils::ParseBoolean(env, argv[0], value)) {
1569 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1570 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "boolean"));
1571 return result;
1572 }
1573
1574 WebMessageExt *webMessageExt = nullptr;
1575 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1576 if ((!webMessageExt) || (status != napi_ok)) {
1577 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1578 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1579 return result;
1580 }
1581
1582 int32_t type = webMessageExt->GetType();
1583 if (type != static_cast<int32_t>(WebMessageType::BOOLEAN)) {
1584 WVLOG_E("web message SetBoolean error type:%{public}d", type);
1585 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1586 return result;
1587 }
1588 webMessageExt->SetBoolean(value);
1589 return result;
1590 }
1591
SetArrayBuffer(napi_env env,napi_callback_info info)1592 napi_value NapiWebMessageExt::SetArrayBuffer(napi_env env, napi_callback_info info)
1593 {
1594 WVLOG_D("NapiWebMessageExt::SetArrayBuffer start");
1595 napi_value thisVar = nullptr;
1596 napi_value result = nullptr;
1597 size_t argc = INTEGER_ONE;
1598 napi_value argv[INTEGER_ONE] = { 0 };
1599 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1600 if (argc != INTEGER_ONE) {
1601 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1602 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1603 return result;
1604 }
1605
1606 bool isArrayBuffer = false;
1607 NAPI_CALL(env, napi_is_arraybuffer(env, argv[INTEGER_ZERO], &isArrayBuffer));
1608 if (!isArrayBuffer) {
1609 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1610 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "arrayBuffer"));
1611 return result;
1612 }
1613
1614 uint8_t *arrBuf = nullptr;
1615 size_t byteLength = 0;
1616 napi_get_arraybuffer_info(env, argv[INTEGER_ZERO], (void**)&arrBuf, &byteLength);
1617 std::vector<uint8_t> vecData(arrBuf, arrBuf + byteLength);
1618 WebMessageExt *webMessageExt = nullptr;
1619 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1620 if ((!webMessageExt) || (status != napi_ok)) {
1621 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1622 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1623 return result;
1624 }
1625
1626 int32_t type = webMessageExt->GetType();
1627 if (type != static_cast<int32_t>(WebMessageType::ARRAYBUFFER)) {
1628 WVLOG_E("web message SetArrayBuffer error type:%{public}d", type);
1629 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1630 return result;
1631 }
1632 webMessageExt->SetArrayBuffer(vecData);
1633 return result;
1634 }
1635
SetArray(napi_env env,napi_callback_info info)1636 napi_value NapiWebMessageExt::SetArray(napi_env env, napi_callback_info info)
1637 {
1638 WVLOG_D("NapiWebMessageExt::SetArray start");
1639 napi_value thisVar = nullptr;
1640 napi_value result = nullptr;
1641 size_t argc = INTEGER_ONE;
1642 napi_value argv[INTEGER_ONE] = { 0 };
1643 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1644 if (argc != INTEGER_ONE) {
1645 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1646 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1647 return result;
1648 }
1649 bool isArray = false;
1650 NAPI_CALL(env, napi_is_array(env, argv[INTEGER_ZERO], &isArray));
1651 if (!isArray) {
1652 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1653 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "array"));
1654 return result;
1655 }
1656 WebMessageExt *webMessageExt = nullptr;
1657 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1658 if ((!webMessageExt) || (status != napi_ok)) {
1659 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1660 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1661 return result;
1662 }
1663 int32_t type = webMessageExt->GetType();
1664 if (type != static_cast<int32_t>(WebMessageType::ARRAY)) {
1665 WVLOG_E("web message SetArray error type:%{public}d", type);
1666 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1667 return result;
1668 }
1669 bool isDouble = false;
1670 napi_valuetype valueType = GetArrayValueType(env, argv[INTEGER_ZERO], isDouble);
1671 if (valueType == napi_undefined) {
1672 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1673 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "number"));
1674 return result;
1675 }
1676 using SetArrayHandler = std::function<void(napi_env, napi_value, WebMessageExt*)>;
1677 const std::unordered_map<napi_valuetype, SetArrayHandler> functionMap = {
1678 { napi_boolean, SetArrayHandlerBoolean },
1679 { napi_string, SetArrayHandlerString },
1680 { napi_number, [isDouble](napi_env env, napi_value array, WebMessageExt* msgExt) {
1681 isDouble ? SetArrayHandlerDouble(env, array, msgExt)
1682 : SetArrayHandlerInteger(env, array, msgExt);
1683 } }
1684 };
1685 auto it = functionMap.find(valueType);
1686 if (it != functionMap.end()) {
1687 it->second(env, argv[INTEGER_ZERO], webMessageExt);
1688 }
1689 return result;
1690 }
1691
SetError(napi_env env,napi_callback_info info)1692 napi_value NapiWebMessageExt::SetError(napi_env env, napi_callback_info info)
1693 {
1694 WVLOG_D("NapiWebMessageExt::SetError start");
1695 napi_value thisVar = nullptr;
1696 napi_value result = nullptr;
1697 size_t argc = INTEGER_ONE;
1698 napi_value argv[INTEGER_ONE] = { 0 };
1699 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1700 if (argc != INTEGER_ONE) {
1701 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1702 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1703 return result;
1704 }
1705
1706 bool isError = false;
1707 NAPI_CALL(env, napi_is_error(env, argv[INTEGER_ZERO], &isError));
1708 if (!isError) {
1709 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1710 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "message", "error"));
1711 return result;
1712 }
1713
1714 napi_value nameObj = 0;
1715 napi_get_named_property(env, argv[INTEGER_ZERO], "name", &nameObj);
1716 std::string nameVal;
1717 if (!NapiParseUtils::ParseString(env, nameObj, nameVal)) {
1718 return result;
1719 }
1720
1721 napi_value msgObj = 0;
1722 napi_get_named_property(env, argv[INTEGER_ZERO], "message", &msgObj);
1723 std::string msgVal;
1724 if (!NapiParseUtils::ParseString(env, msgObj, msgVal)) {
1725 return result;
1726 }
1727
1728 WebMessageExt *webMessageExt = nullptr;
1729 napi_status status = napi_unwrap(env, thisVar, (void **)&webMessageExt);
1730 if ((!webMessageExt) || (status != napi_ok)) {
1731 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1732 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
1733 return result;
1734 }
1735
1736 int32_t type = webMessageExt->GetType();
1737 if (type != static_cast<int32_t>(WebMessageType::ERROR)) {
1738 WVLOG_E("web message SetError error type:%{public}d", type);
1739 BusinessError::ThrowErrorByErrcode(env, TYPE_NOT_MATCH_WITCH_VALUE);
1740 return result;
1741 }
1742 webMessageExt->SetError(nameVal, msgVal);
1743 return result;
1744 }
1745
CreateWebMessagePorts(napi_env env,napi_callback_info info)1746 napi_value NapiWebviewController::CreateWebMessagePorts(napi_env env, napi_callback_info info)
1747 {
1748 WVLOG_D("create web message port");
1749 napi_value thisVar = nullptr;
1750 napi_value result = nullptr;
1751 size_t argc = INTEGER_ONE;
1752 napi_value argv[INTEGER_ONE] = { 0 };
1753 bool isExtentionType = false;
1754 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1755 if (argc != INTEGER_ZERO && argc != INTEGER_ONE) {
1756 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1757 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "zero", "one"));
1758 return result;
1759 }
1760
1761 if (argc == INTEGER_ONE) {
1762 if (!NapiParseUtils::ParseBoolean(env, argv[0], isExtentionType)) {
1763 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1764 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "isExtentionType", "boolean"));
1765 return result;
1766 }
1767 }
1768
1769 WebviewController *webviewController = nullptr;
1770 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
1771 if (webviewController == nullptr || !webviewController->IsInit()) {
1772 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
1773 WVLOG_E("create message port failed, napi unwrap webviewController failed");
1774 return nullptr;
1775 }
1776 int32_t nwebId = webviewController->GetWebId();
1777 std::vector<std::string> ports = webviewController->CreateWebMessagePorts();
1778 if (ports.size() != INTEGER_TWO) {
1779 WVLOG_E("create web message port failed");
1780 return result;
1781 }
1782 napi_value msgPortcons = nullptr;
1783 NAPI_CALL(env, napi_get_reference_value(env, g_classWebMsgPort, &msgPortcons));
1784 napi_create_array(env, &result);
1785 napi_value consParam[INTEGER_TWO][INTEGER_THREE] = {{0}};
1786 for (uint32_t i = 0; i < INTEGER_TWO; i++) {
1787 napi_value msgPortObj = nullptr;
1788 NAPI_CALL(env, napi_create_int32(env, nwebId, &consParam[i][INTEGER_ZERO]));
1789 NAPI_CALL(env, napi_create_string_utf8(env, ports[i].c_str(), ports[i].length(), &consParam[i][INTEGER_ONE]));
1790 NAPI_CALL(env, napi_get_boolean(env, isExtentionType, &consParam[i][INTEGER_TWO]));
1791 NAPI_CALL(env, napi_new_instance(env, msgPortcons, INTEGER_THREE, consParam[i], &msgPortObj));
1792 napi_value jsExtention;
1793 napi_get_boolean(env, isExtentionType, &jsExtention);
1794 napi_set_named_property(env, msgPortObj, "isExtentionType", jsExtention);
1795
1796 napi_set_element(env, result, i, msgPortObj);
1797 }
1798
1799 return result;
1800 }
1801
GetSendPorts(napi_env env,napi_value argv,std::vector<std::string> & sendPorts)1802 bool GetSendPorts(napi_env env, napi_value argv, std::vector<std::string>& sendPorts)
1803 {
1804 uint32_t arrayLen = 0;
1805 napi_get_array_length(env, argv, &arrayLen);
1806 if (arrayLen == 0) {
1807 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1808 return false;
1809 }
1810
1811 napi_valuetype valueType = napi_undefined;
1812 for (uint32_t i = 0; i < arrayLen; i++) {
1813 napi_value portItem = nullptr;
1814 napi_get_element(env, argv, i, &portItem);
1815 napi_typeof(env, portItem, &valueType);
1816 if (valueType != napi_object) {
1817 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1818 return false;
1819 }
1820 WebMessagePort *msgPort = nullptr;
1821 napi_status status = napi_unwrap(env, portItem, (void **)&msgPort);
1822 if ((!msgPort) || (status != napi_ok)) {
1823 WVLOG_E("post port to html failed, napi unwrap msg port fail");
1824 return false;
1825 }
1826 std::string portHandle = msgPort->GetPortHandle();
1827 sendPorts.emplace_back(portHandle);
1828 }
1829 return true;
1830 }
1831
PostMessage(napi_env env,napi_callback_info info)1832 napi_value NapiWebviewController::PostMessage(napi_env env, napi_callback_info info)
1833 {
1834 WVLOG_D("post message port");
1835 napi_value thisVar = nullptr;
1836 napi_value result = nullptr;
1837 size_t argc = INTEGER_THREE;
1838 napi_value argv[INTEGER_THREE];
1839 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1840 if (argc != INTEGER_THREE) {
1841 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1842 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "three"));
1843 return result;
1844 }
1845
1846 std::string portName;
1847 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], portName)) {
1848 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1849 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "name", "string"));
1850 return result;
1851 }
1852
1853 bool isArray = false;
1854 NAPI_CALL(env, napi_is_array(env, argv[INTEGER_ONE], &isArray));
1855 if (!isArray) {
1856 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1857 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "ports", "array"));
1858 return result;
1859 }
1860 std::vector<std::string> sendPorts;
1861 if (!GetSendPorts(env, argv[INTEGER_ONE], sendPorts)) {
1862 WVLOG_E("post port to html failed, getSendPorts fail");
1863 return result;
1864 }
1865
1866 std::string urlStr;
1867 if (!NapiParseUtils::ParseString(env, argv[INTEGER_TWO], urlStr)) {
1868 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1869 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "uri", "string"));
1870 return result;
1871 }
1872
1873 WebviewController *webviewController = nullptr;
1874 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
1875 if (webviewController == nullptr || !webviewController->IsInit()) {
1876 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
1877 WVLOG_E("post port to html failed, napi unwrap webviewController failed");
1878 return nullptr;
1879 }
1880
1881 webviewController->PostWebMessage(portName, sendPorts, urlStr);
1882 NAPI_CALL(env, napi_get_undefined(env, &result));
1883
1884 return result;
1885 }
1886
JsConstructor(napi_env env,napi_callback_info info)1887 napi_value NapiWebMessagePort::JsConstructor(napi_env env, napi_callback_info info)
1888 {
1889 WVLOG_D("web message port construct");
1890 napi_value thisVar = nullptr;
1891 size_t argc = INTEGER_THREE;
1892 napi_value argv[INTEGER_THREE] = {0};
1893 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
1894
1895 int32_t webId = -1;
1896 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], webId)) {
1897 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1898 return nullptr;
1899 }
1900
1901 std::string portHandle;
1902 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ONE], portHandle)) {
1903 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1904 return nullptr;
1905 }
1906
1907 bool isExtentionType = false;
1908 if (!NapiParseUtils::ParseBoolean(env, argv[INTEGER_TWO], isExtentionType)) {
1909 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1910 return nullptr;
1911 }
1912
1913 WebMessagePort *msgPort = new (std::nothrow) WebMessagePort(webId, portHandle, isExtentionType);
1914 if (msgPort == nullptr) {
1915 WVLOG_E("new msg port failed");
1916 return nullptr;
1917 }
1918 NAPI_CALL(env, napi_wrap(env, thisVar, msgPort,
1919 [](napi_env env, void *data, void *hint) {
1920 WebMessagePort *msgPort = static_cast<WebMessagePort *>(data);
1921 delete msgPort;
1922 },
1923 nullptr, nullptr));
1924 return thisVar;
1925 }
1926
Close(napi_env env,napi_callback_info info)1927 napi_value NapiWebMessagePort::Close(napi_env env, napi_callback_info info)
1928 {
1929 WVLOG_D("close message port");
1930 napi_value thisVar = nullptr;
1931 napi_value result = nullptr;
1932 NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr));
1933
1934 WebMessagePort *msgPort = nullptr;
1935 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort));
1936 if (msgPort == nullptr) {
1937 WVLOG_E("close message port failed, napi unwrap msg port failed");
1938 return nullptr;
1939 }
1940 ErrCode ret = msgPort->ClosePort();
1941 if (ret != NO_ERROR) {
1942 BusinessError::ThrowErrorByErrcode(env, ret);
1943 return result;
1944 }
1945 NAPI_CALL(env, napi_get_undefined(env, &result));
1946
1947 return result;
1948 }
1949
PostMessageEventMsgHandler(napi_env env,napi_value argv,napi_valuetype valueType,bool isArrayBuffer,std::shared_ptr<NWebMessage> webMsg)1950 bool PostMessageEventMsgHandler(napi_env env, napi_value argv, napi_valuetype valueType, bool isArrayBuffer,
1951 std::shared_ptr<NWebMessage> webMsg)
1952 {
1953 if (valueType == napi_string) {
1954 size_t bufferSize = 0;
1955 napi_get_value_string_utf8(env, argv, nullptr, 0, &bufferSize);
1956 if (bufferSize > UINT_MAX) {
1957 WVLOG_E("String length is too long");
1958 return false;
1959 }
1960 char* stringValue = new (std::nothrow) char[bufferSize + 1];
1961 if (stringValue == nullptr) {
1962 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
1963 return false;
1964 }
1965 size_t jsStringLength = 0;
1966 napi_get_value_string_utf8(env, argv, stringValue, bufferSize + 1, &jsStringLength);
1967 std::string message(stringValue);
1968 delete [] stringValue;
1969 stringValue = nullptr;
1970
1971 webMsg->SetType(NWebValue::Type::STRING);
1972 webMsg->SetString(message);
1973 } else if (isArrayBuffer) {
1974 uint8_t *arrBuf = nullptr;
1975 size_t byteLength = 0;
1976 napi_get_arraybuffer_info(env, argv, (void**)&arrBuf, &byteLength);
1977 std::vector<uint8_t> vecData(arrBuf, arrBuf + byteLength);
1978 webMsg->SetType(NWebValue::Type::BINARY);
1979 webMsg->SetBinary(vecData);
1980 }
1981 return true;
1982 }
1983
PostMessageEvent(napi_env env,napi_callback_info info)1984 napi_value NapiWebMessagePort::PostMessageEvent(napi_env env, napi_callback_info info)
1985 {
1986 WVLOG_D("message port post message");
1987 napi_value thisVar = nullptr;
1988 napi_value result = nullptr;
1989 size_t argc = INTEGER_ONE;
1990 napi_value argv[INTEGER_ONE];
1991 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
1992 if (argc != INTEGER_ONE) {
1993 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
1994 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
1995 return result;
1996 }
1997 napi_valuetype valueType = napi_undefined;
1998 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
1999
2000 bool isArrayBuffer = false;
2001 NAPI_CALL(env, napi_is_arraybuffer(env, argv[INTEGER_ZERO], &isArrayBuffer));
2002 if (valueType != napi_string && !isArrayBuffer) {
2003 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2004 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
2005 return result;
2006 }
2007
2008 auto webMsg = std::make_shared<OHOS::NWeb::NWebMessage>(NWebValue::Type::NONE);
2009 if (!PostMessageEventMsgHandler(env, argv[INTEGER_ZERO], valueType, isArrayBuffer, webMsg)) {
2010 WVLOG_E("post message failed, PostMessageEventMsgHandler failed");
2011 return result;
2012 }
2013
2014 WebMessagePort *msgPort = nullptr;
2015 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort));
2016 if (msgPort == nullptr) {
2017 WVLOG_E("post message failed, napi unwrap msg port failed");
2018 return nullptr;
2019 }
2020 ErrCode ret = msgPort->PostPortMessage(webMsg);
2021 if (ret != NO_ERROR) {
2022 BusinessError::ThrowErrorByErrcode(env, ret);
2023 return result;
2024 }
2025 NAPI_CALL(env, napi_get_undefined(env, &result));
2026
2027 return result;
2028 }
2029
PostMessageEventExt(napi_env env,napi_callback_info info)2030 napi_value NapiWebMessagePort::PostMessageEventExt(napi_env env, napi_callback_info info)
2031 {
2032 WVLOG_D("message PostMessageEventExt start");
2033 napi_value thisVar = nullptr;
2034 napi_value result = nullptr;
2035 size_t argc = INTEGER_ONE;
2036 napi_value argv[INTEGER_ONE];
2037 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
2038 if (argc != INTEGER_ONE) {
2039 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2040 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2041 return result;
2042 }
2043 napi_valuetype valueType = napi_undefined;
2044 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
2045 if (valueType != napi_object) {
2046 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2047 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
2048 return result;
2049 }
2050
2051 WebMessageExt *webMessageExt = nullptr;
2052 NAPI_CALL(env, napi_unwrap(env, argv[INTEGER_ZERO], (void **)&webMessageExt));
2053 if (webMessageExt == nullptr) {
2054 WVLOG_E("post message failed, napi unwrap msg port failed");
2055 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2056 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NOT_NULL, "message"));
2057 return nullptr;
2058 }
2059
2060 WebMessagePort *msgPort = nullptr;
2061 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort));
2062 if (msgPort == nullptr) {
2063 WVLOG_E("post message failed, napi unwrap msg port failed");
2064 return nullptr;
2065 }
2066
2067 if (!msgPort->IsExtentionType()) {
2068 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2069 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "message"));
2070 return result;
2071 }
2072
2073 ErrCode ret = msgPort->PostPortMessage(webMessageExt->GetData());
2074 if (ret != NO_ERROR) {
2075 BusinessError::ThrowErrorByErrcode(env, ret);
2076 return result;
2077 }
2078 NAPI_CALL(env, napi_get_undefined(env, &result));
2079
2080 return result;
2081 }
2082
2083
OnMessageEventExt(napi_env env,napi_callback_info info)2084 napi_value NapiWebMessagePort::OnMessageEventExt(napi_env env, napi_callback_info info)
2085 {
2086 WVLOG_D("message port set OnMessageEventExt callback");
2087 napi_value thisVar = nullptr;
2088 napi_value result = nullptr;
2089 size_t argc = INTEGER_ONE;
2090 napi_value argv[INTEGER_ONE];
2091 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
2092 if (argc != INTEGER_ONE) {
2093 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2094 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2095 return result;
2096 }
2097 napi_valuetype valueType = napi_undefined;
2098 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
2099 if (valueType != napi_function) {
2100 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2101 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "callback", "function"));
2102 return result;
2103 }
2104
2105 napi_ref onMsgEventFunc = nullptr;
2106 NAPI_CALL(env, napi_create_reference(env, argv[INTEGER_ZERO], INTEGER_ONE, &onMsgEventFunc));
2107
2108 auto callbackImpl = std::make_shared<NWebValueCallbackImpl>(env, onMsgEventFunc, true);
2109
2110 WebMessagePort *msgPort = nullptr;
2111 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort));
2112 if (msgPort == nullptr) {
2113 WVLOG_E("set message event callback failed, napi unwrap msg port failed");
2114 napi_delete_reference(env, onMsgEventFunc);
2115 return nullptr;
2116 }
2117 ErrCode ret = msgPort->SetPortMessageCallback(callbackImpl);
2118 if (ret != NO_ERROR) {
2119 BusinessError::ThrowErrorByErrcode(env, ret);
2120 }
2121 NAPI_CALL(env, napi_get_undefined(env, &result));
2122 return result;
2123 }
2124
UvWebMsgOnReceiveCbDataHandler(NapiWebMessagePort::WebMsgPortParam * data,napi_value & result)2125 bool UvWebMsgOnReceiveCbDataHandler(NapiWebMessagePort::WebMsgPortParam *data, napi_value& result)
2126 {
2127 if (data->extention_) {
2128 napi_value webMsgExt = nullptr;
2129 napi_status status = napi_get_reference_value(data->env_, g_webMsgExtClassRef, &webMsgExt);
2130 if (status != napi_status::napi_ok) {
2131 WVLOG_E("napi_get_reference_value failed.");
2132 return false;
2133 }
2134 status = napi_new_instance(data->env_, webMsgExt, 0, NULL, &result);
2135 if (status != napi_status::napi_ok) {
2136 WVLOG_E("napi_new_instance failed.");
2137 return false;
2138 }
2139
2140 WebMessageExt *webMessageExt = new (std::nothrow) WebMessageExt(data->msg_);
2141 if (webMessageExt == nullptr) {
2142 WVLOG_E("new WebMessageExt failed.");
2143 return false;
2144 }
2145
2146 status = napi_wrap(data->env_, result, webMessageExt,
2147 [](napi_env env, void *data, void *hint) {
2148 WebMessageExt *webMessageExt = static_cast<WebMessageExt *>(data);
2149 delete webMessageExt;
2150 },
2151 nullptr, nullptr);
2152 if (status != napi_status::napi_ok) {
2153 WVLOG_E("napi_wrap failed.");
2154 return false;
2155 }
2156 } else {
2157 NapiParseUtils::ConvertNWebToNapiValue(data->env_, data->msg_, result);
2158 }
2159 return true;
2160 }
2161
UvWebMessageOnReceiveValueCallback(uv_work_t * work,int status)2162 void NWebValueCallbackImpl::UvWebMessageOnReceiveValueCallback(uv_work_t *work, int status)
2163 {
2164 if (work == nullptr) {
2165 WVLOG_E("uv work is null");
2166 return;
2167 }
2168 NapiWebMessagePort::WebMsgPortParam *data = reinterpret_cast<NapiWebMessagePort::WebMsgPortParam*>(work->data);
2169 if (data == nullptr) {
2170 WVLOG_E("WebMsgPortParam is null");
2171 delete work;
2172 work = nullptr;
2173 return;
2174 }
2175 napi_handle_scope scope = nullptr;
2176 napi_open_handle_scope(data->env_, &scope);
2177 if (scope == nullptr) {
2178 delete work;
2179 work = nullptr;
2180 return;
2181 }
2182 napi_value result[INTEGER_ONE] = {0};
2183 if (!UvWebMsgOnReceiveCbDataHandler(data, result[INTEGER_ZERO])) {
2184 delete work;
2185 work = nullptr;
2186 napi_close_handle_scope(data->env_, scope);
2187 return;
2188 }
2189
2190 napi_value onMsgEventFunc = nullptr;
2191 napi_get_reference_value(data->env_, data->callback_, &onMsgEventFunc);
2192 napi_value placeHodler = nullptr;
2193 napi_call_function(data->env_, nullptr, onMsgEventFunc, INTEGER_ONE, &result[INTEGER_ZERO], &placeHodler);
2194
2195 std::unique_lock<std::mutex> lock(data->mutex_);
2196 data->ready_ = true;
2197 data->condition_.notify_all();
2198 napi_close_handle_scope(data->env_, scope);
2199 }
2200
InvokeWebMessageCallback(NapiWebMessagePort::WebMsgPortParam * data)2201 static void InvokeWebMessageCallback(NapiWebMessagePort::WebMsgPortParam *data)
2202 {
2203 napi_handle_scope scope = nullptr;
2204 napi_open_handle_scope(data->env_, &scope);
2205 if (scope == nullptr) {
2206 WVLOG_E("scope is null");
2207 return;
2208 }
2209 napi_value result[INTEGER_ONE] = {0};
2210 if (!UvWebMsgOnReceiveCbDataHandler(data, result[INTEGER_ZERO])) {
2211 WVLOG_E("get result failed");
2212 napi_close_handle_scope(data->env_, scope);
2213 return;
2214 }
2215
2216 napi_value onMsgEventFunc = nullptr;
2217 napi_get_reference_value(data->env_, data->callback_, &onMsgEventFunc);
2218 napi_value placeHodler = nullptr;
2219 napi_call_function(data->env_, nullptr, onMsgEventFunc, INTEGER_ONE, &result[INTEGER_ZERO], &placeHodler);
2220
2221 napi_close_handle_scope(data->env_, scope);
2222 }
2223
OnReceiveValue(std::shared_ptr<NWebMessage> result)2224 void NWebValueCallbackImpl::OnReceiveValue(std::shared_ptr<NWebMessage> result)
2225 {
2226 WVLOG_D("message port received msg");
2227 uv_loop_s *loop = nullptr;
2228 uv_work_t *work = nullptr;
2229 napi_get_uv_event_loop(env_, &loop);
2230 auto engine = reinterpret_cast<NativeEngine*>(env_);
2231 if (loop == nullptr) {
2232 WVLOG_E("get uv event loop failed");
2233 return;
2234 }
2235 work = new (std::nothrow) uv_work_t;
2236 if (work == nullptr) {
2237 WVLOG_E("new uv work failed");
2238 return;
2239 }
2240 NapiWebMessagePort::WebMsgPortParam *param = new (std::nothrow) NapiWebMessagePort::WebMsgPortParam();
2241 if (param == nullptr) {
2242 WVLOG_E("new WebMsgPortParam failed");
2243 delete work;
2244 return;
2245 }
2246 param->env_ = env_;
2247 param->callback_ = callback_;
2248 param->msg_ = result;
2249 param->extention_ = extention_;
2250 if (pthread_self() == engine->GetTid()) {
2251 InvokeWebMessageCallback(param);
2252 } else {
2253 work->data = reinterpret_cast<void*>(param);
2254 uv_queue_work_with_qos(
2255 loop, work, [](uv_work_t* work) {}, UvWebMessageOnReceiveValueCallback, uv_qos_user_initiated);
2256
2257 {
2258 std::unique_lock<std::mutex> lock(param->mutex_);
2259 param->condition_.wait(lock, [¶m] { return param->ready_; });
2260 }
2261 }
2262
2263 if (param != nullptr) {
2264 delete param;
2265 param = nullptr;
2266 }
2267 if (work != nullptr) {
2268 delete work;
2269 work = nullptr;
2270 }
2271 }
2272
UvNWebValueCallbackImplThreadWoker(uv_work_t * work,int status)2273 void UvNWebValueCallbackImplThreadWoker(uv_work_t *work, int status)
2274 {
2275 if (work == nullptr) {
2276 WVLOG_E("uv work is null");
2277 return;
2278 }
2279 NapiWebMessagePort::WebMsgPortParam *data = reinterpret_cast<NapiWebMessagePort::WebMsgPortParam*>(work->data);
2280 if (data == nullptr) {
2281 WVLOG_E("WebMsgPortParam is null");
2282 delete work;
2283 return;
2284 }
2285
2286 napi_delete_reference(data->env_, data->callback_);
2287 delete data;
2288 data = nullptr;
2289 delete work;
2290 work = nullptr;
2291 }
2292
~NWebValueCallbackImpl()2293 NWebValueCallbackImpl::~NWebValueCallbackImpl()
2294 {
2295 WVLOG_D("~NWebValueCallbackImpl");
2296 uv_loop_s *loop = nullptr;
2297 uv_work_t *work = nullptr;
2298 napi_get_uv_event_loop(env_, &loop);
2299 if (loop == nullptr) {
2300 WVLOG_E("get uv event loop failed");
2301 return;
2302 }
2303 work = new (std::nothrow) uv_work_t;
2304 if (work == nullptr) {
2305 WVLOG_E("new uv work failed");
2306 return;
2307 }
2308 NapiWebMessagePort::WebMsgPortParam *param = new (std::nothrow) NapiWebMessagePort::WebMsgPortParam();
2309 if (param == nullptr) {
2310 WVLOG_E("new WebMsgPortParam failed");
2311 delete work;
2312 return;
2313 }
2314 param->env_ = env_;
2315 param->callback_ = callback_;
2316 work->data = reinterpret_cast<void*>(param);
2317 int ret = uv_queue_work_with_qos(
2318 loop, work, [](uv_work_t *work) {}, UvNWebValueCallbackImplThreadWoker, uv_qos_user_initiated);
2319 if (ret != 0) {
2320 if (param != nullptr) {
2321 delete param;
2322 param = nullptr;
2323 }
2324 if (work != nullptr) {
2325 delete work;
2326 work = nullptr;
2327 }
2328 }
2329 }
2330
OnMessageEvent(napi_env env,napi_callback_info info)2331 napi_value NapiWebMessagePort::OnMessageEvent(napi_env env, napi_callback_info info)
2332 {
2333 WVLOG_D("message port set OnMessageEvent callback");
2334 napi_value thisVar = nullptr;
2335 napi_value result = nullptr;
2336 size_t argc = INTEGER_ONE;
2337 napi_value argv[INTEGER_ONE];
2338 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
2339 if (argc != INTEGER_ONE) {
2340 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2341 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2342 return result;
2343 }
2344 napi_valuetype valueType = napi_undefined;
2345 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
2346 if (valueType != napi_function) {
2347 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2348 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "callback", "function"));
2349 return result;
2350 }
2351
2352 napi_ref onMsgEventFunc = nullptr;
2353 NAPI_CALL(env, napi_create_reference(env, argv[INTEGER_ZERO], INTEGER_ONE, &onMsgEventFunc));
2354
2355 auto callbackImpl = std::make_shared<NWebValueCallbackImpl>(env, onMsgEventFunc, false);
2356
2357 WebMessagePort *msgPort = nullptr;
2358 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&msgPort));
2359 if (msgPort == nullptr) {
2360 WVLOG_E("set message event callback failed, napi unwrap msg port failed");
2361 return nullptr;
2362 }
2363 ErrCode ret = msgPort->SetPortMessageCallback(callbackImpl);
2364 if (ret != NO_ERROR) {
2365 BusinessError::ThrowErrorByErrcode(env, ret);
2366 }
2367 NAPI_CALL(env, napi_get_undefined(env, &result));
2368 return result;
2369 }
2370
ZoomIn(napi_env env,napi_callback_info info)2371 napi_value NapiWebviewController::ZoomIn(napi_env env, napi_callback_info info)
2372 {
2373 napi_value result = nullptr;
2374 WebviewController *webviewController = GetWebviewController(env, info);
2375 if (!webviewController) {
2376 return nullptr;
2377 }
2378
2379 ErrCode ret = webviewController->ZoomIn();
2380 if (ret != NO_ERROR) {
2381 if (ret == NWEB_ERROR) {
2382 WVLOG_E("ZoomIn failed.");
2383 return nullptr;
2384 }
2385 BusinessError::ThrowErrorByErrcode(env, ret);
2386 }
2387
2388 NAPI_CALL(env, napi_get_undefined(env, &result));
2389 return result;
2390 }
2391
ZoomOut(napi_env env,napi_callback_info info)2392 napi_value NapiWebviewController::ZoomOut(napi_env env, napi_callback_info info)
2393 {
2394 napi_value result = nullptr;
2395 WebviewController *webviewController = GetWebviewController(env, info);
2396 if (!webviewController) {
2397 return nullptr;
2398 }
2399
2400 ErrCode ret = webviewController->ZoomOut();
2401 if (ret != NO_ERROR) {
2402 if (ret == NWEB_ERROR) {
2403 WVLOG_E("ZoomOut failed.");
2404 return nullptr;
2405 }
2406 BusinessError::ThrowErrorByErrcode(env, ret);
2407 }
2408
2409 NAPI_CALL(env, napi_get_undefined(env, &result));
2410 return result;
2411 }
2412
GetWebId(napi_env env,napi_callback_info info)2413 napi_value NapiWebviewController::GetWebId(napi_env env, napi_callback_info info)
2414 {
2415 napi_value result = nullptr;
2416 WebviewController *webviewController = GetWebviewController(env, info);
2417 if (!webviewController) {
2418 return nullptr;
2419 }
2420
2421 int32_t webId = webviewController->GetWebId();
2422 napi_create_int32(env, webId, &result);
2423
2424 return result;
2425 }
2426
GetUserAgent(napi_env env,napi_callback_info info)2427 napi_value NapiWebviewController::GetUserAgent(napi_env env, napi_callback_info info)
2428 {
2429 napi_value result = nullptr;
2430 WebviewController *webviewController = GetWebviewController(env, info);
2431 if (!webviewController) {
2432 return nullptr;
2433 }
2434
2435 std::string userAgent = "";
2436 userAgent = webviewController->GetUserAgent();
2437 napi_create_string_utf8(env, userAgent.c_str(), userAgent.length(), &result);
2438
2439 return result;
2440 }
2441
GetCustomUserAgent(napi_env env,napi_callback_info info)2442 napi_value NapiWebviewController::GetCustomUserAgent(napi_env env, napi_callback_info info)
2443 {
2444 napi_value thisVar = nullptr;
2445 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
2446
2447 WebviewController *webviewController = nullptr;
2448 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2449 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2450 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2451 return nullptr;
2452 }
2453
2454 napi_value result = nullptr;
2455 std::string userAgent = webviewController->GetCustomUserAgent();
2456 napi_create_string_utf8(env, userAgent.c_str(), userAgent.length(), &result);
2457 return result;
2458 }
2459
SetCustomUserAgent(napi_env env,napi_callback_info info)2460 napi_value NapiWebviewController::SetCustomUserAgent(napi_env env, napi_callback_info info)
2461 {
2462 napi_value thisVar = nullptr;
2463 napi_value result = nullptr;
2464 size_t argc = INTEGER_ONE;
2465 napi_value argv[INTEGER_ONE];
2466 NAPI_CALL(env, napi_get_undefined(env, &result));
2467
2468 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2469 if (argc != INTEGER_ONE) {
2470 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2471 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2472 return result;
2473 }
2474
2475 std::string userAgent;
2476 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], userAgent)) {
2477 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2478 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "userAgent", "string"));
2479 return result;
2480 }
2481
2482 WebviewController *webviewController = nullptr;
2483 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2484 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2485 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2486 return result;
2487 }
2488 ErrCode ret = webviewController->SetCustomUserAgent(userAgent);
2489 if (ret != NO_ERROR) {
2490 BusinessError::ThrowErrorByErrcode(env, ret);
2491 }
2492 return result;
2493 }
2494
GetTitle(napi_env env,napi_callback_info info)2495 napi_value NapiWebviewController::GetTitle(napi_env env, napi_callback_info info)
2496 {
2497 napi_value result = nullptr;
2498 WebviewController *webviewController = GetWebviewController(env, info);
2499 if (!webviewController) {
2500 return nullptr;
2501 }
2502
2503 std::string title = "";
2504 title = webviewController->GetTitle();
2505 napi_create_string_utf8(env, title.c_str(), title.length(), &result);
2506
2507 return result;
2508 }
2509
GetPageHeight(napi_env env,napi_callback_info info)2510 napi_value NapiWebviewController::GetPageHeight(napi_env env, napi_callback_info info)
2511 {
2512 napi_value result = nullptr;
2513 WebviewController *webviewController = GetWebviewController(env, info);
2514 if (!webviewController) {
2515 return nullptr;
2516 }
2517
2518 int32_t pageHeight = webviewController->GetPageHeight();
2519 napi_create_int32(env, pageHeight, &result);
2520
2521 return result;
2522 }
2523
BackOrForward(napi_env env,napi_callback_info info)2524 napi_value NapiWebviewController::BackOrForward(napi_env env, napi_callback_info info)
2525 {
2526 napi_value thisVar = nullptr;
2527 napi_value result = nullptr;
2528 size_t argc = INTEGER_ONE;
2529 napi_value argv[INTEGER_ONE] = {0};
2530 void* data = nullptr;
2531 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
2532
2533 if (argc != INTEGER_ONE) {
2534 WVLOG_E("Requires 1 parameters.");
2535 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2536 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2537 return nullptr;
2538 }
2539
2540 int32_t step = -1;
2541 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], step)) {
2542 WVLOG_E("Parameter is not integer number type.");
2543 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2544 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "step", "number"));
2545 return nullptr;
2546 }
2547
2548 WebviewController *webviewController = nullptr;
2549 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2550 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2551 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2552 return nullptr;
2553 }
2554
2555 ErrCode ret = webviewController->BackOrForward(step);
2556 if (ret != NO_ERROR) {
2557 BusinessError::ThrowErrorByErrcode(env, ret);
2558 }
2559
2560 NAPI_CALL(env, napi_get_undefined(env, &result));
2561 return result;
2562 }
2563
StoreWebArchive(napi_env env,napi_callback_info info)2564 napi_value NapiWebviewController::StoreWebArchive(napi_env env, napi_callback_info info)
2565 {
2566 napi_value thisVar = nullptr;
2567 napi_value result = nullptr;
2568 size_t argc = INTEGER_ONE;
2569 size_t argcPromise = INTEGER_TWO;
2570 size_t argcCallback = INTEGER_THREE;
2571 napi_value argv[INTEGER_THREE] = { 0 };
2572
2573 napi_get_undefined(env, &result);
2574 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2575
2576 if (argc != argcPromise && argc != argcCallback) {
2577 BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
2578 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "two", "three"));
2579 return result;
2580 }
2581 std::string baseName;
2582 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], baseName)) {
2583 BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
2584 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "baseName", "string"));
2585 return result;
2586 }
2587
2588 if (baseName.empty()) {
2589 BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
2590 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NOT_NULL, "baseName"));
2591 return result;
2592 }
2593
2594 bool autoName = false;
2595 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2596 if (!NapiParseUtils::ParseBoolean(env, argv[INTEGER_ONE], autoName)) {
2597 BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
2598 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "autoName", "boolean"));
2599 return result;
2600 }
2601
2602 if (argc == argcCallback) {
2603 napi_valuetype valueType = napi_null;
2604 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2605 napi_typeof(env, argv[argcCallback - 1], &valueType);
2606 if (valueType != napi_function) {
2607 BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
2608 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "callback", "function"));
2609 return result;
2610 }
2611 }
2612 return StoreWebArchiveInternal(env, info, baseName, autoName);
2613 }
2614
StoreWebArchiveInternal(napi_env env,napi_callback_info info,const std::string & baseName,bool autoName)2615 napi_value NapiWebviewController::StoreWebArchiveInternal(napi_env env, napi_callback_info info,
2616 const std::string &baseName, bool autoName)
2617 {
2618 napi_value thisVar = nullptr;
2619 size_t argc = INTEGER_ONE;
2620 size_t argcPromise = INTEGER_TWO;
2621 size_t argcCallback = INTEGER_THREE;
2622 napi_value argv[INTEGER_THREE] = {0};
2623
2624 napi_value result = nullptr;
2625 napi_get_undefined(env, &result);
2626 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2627
2628 WebviewController *webviewController = nullptr;
2629 napi_unwrap(env, thisVar, (void **)&webviewController);
2630
2631 if (!webviewController || !webviewController->IsInit()) {
2632 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2633 return result;
2634 }
2635
2636 if (argc == argcCallback) {
2637 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2638 napi_ref jsCallback = nullptr;
2639 napi_create_reference(env, argv[argcCallback - 1], 1, &jsCallback);
2640
2641 if (jsCallback) {
2642 webviewController->StoreWebArchiveCallback(baseName, autoName, env, std::move(jsCallback));
2643 }
2644 return result;
2645 } else if (argc == argcPromise) {
2646 napi_deferred deferred = nullptr;
2647 napi_value promise = nullptr;
2648 napi_create_promise(env, &deferred, &promise);
2649 if (promise && deferred) {
2650 webviewController->StoreWebArchivePromise(baseName, autoName, env, deferred);
2651 }
2652 return promise;
2653 }
2654 return result;
2655 }
2656
GetHitTestValue(napi_env env,napi_callback_info info)2657 napi_value NapiWebviewController::GetHitTestValue(napi_env env, napi_callback_info info)
2658 {
2659 napi_value result = nullptr;
2660 WebviewController *webviewController = GetWebviewController(env, info);
2661 if (!webviewController) {
2662 return nullptr;
2663 }
2664
2665 std::shared_ptr<HitTestResult> nwebResult = webviewController->GetHitTestValue();
2666
2667 napi_create_object(env, &result);
2668
2669 napi_value type;
2670 if (nwebResult) {
2671 napi_create_uint32(env, nwebResult->GetType(), &type);
2672 } else {
2673 napi_create_uint32(env, HitTestResult::UNKNOWN_TYPE, &type);
2674 }
2675 napi_set_named_property(env, result, "type", type);
2676
2677 napi_value extra;
2678 if (nwebResult) {
2679 napi_create_string_utf8(env, nwebResult->GetExtra().c_str(), NAPI_AUTO_LENGTH, &extra);
2680 } else {
2681 napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &extra);
2682 }
2683 napi_set_named_property(env, result, "extra", extra);
2684
2685 return result;
2686 }
2687
RequestFocus(napi_env env,napi_callback_info info)2688 napi_value NapiWebviewController::RequestFocus(napi_env env, napi_callback_info info)
2689 {
2690 napi_value result = nullptr;
2691 WebviewController *webviewController = GetWebviewController(env, info);
2692 if (!webviewController) {
2693 return nullptr;
2694 }
2695
2696 webviewController->RequestFocus();
2697 NAPI_CALL(env, napi_get_undefined(env, &result));
2698 return result;
2699 }
2700
PostUrl(napi_env env,napi_callback_info info)2701 napi_value NapiWebviewController::PostUrl(napi_env env, napi_callback_info info)
2702 {
2703 WVLOG_D("NapiWebMessageExt::PostUrl start");
2704 napi_value thisVar = nullptr;
2705 napi_value result = nullptr;
2706 size_t argc = INTEGER_TWO;
2707 napi_value argv[INTEGER_TWO] = { 0 };
2708 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2709 if (argc != INTEGER_TWO) {
2710 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2711 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
2712 return result;
2713 }
2714
2715 WebviewController *webviewController = nullptr;
2716 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2717 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2718 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2719 return nullptr;
2720 }
2721
2722 std::string url;
2723 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], url)) {
2724 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2725 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "url", "string"));
2726 return result;
2727 }
2728
2729 bool isArrayBuffer = false;
2730 NAPI_CALL(env, napi_is_arraybuffer(env, argv[INTEGER_ONE], &isArrayBuffer));
2731 if (!isArrayBuffer) {
2732 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2733 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "postData", "array"));
2734 return result;
2735 }
2736
2737 char *arrBuf = nullptr;
2738 size_t byteLength = 0;
2739 napi_get_arraybuffer_info(env, argv[INTEGER_ONE], (void **)&arrBuf, &byteLength);
2740
2741 std::vector<char> postData(arrBuf, arrBuf + byteLength);
2742 ErrCode ret = webviewController->PostUrl(url, postData);
2743 if (ret != NO_ERROR) {
2744 if (ret == NWEB_ERROR) {
2745 WVLOG_E("PostData failed");
2746 return result;
2747 }
2748 BusinessError::ThrowErrorByErrcode(env, ret);
2749 return result;
2750 }
2751 NAPI_CALL(env, napi_get_undefined(env, &result));
2752 return result;
2753 }
2754
LoadUrl(napi_env env,napi_callback_info info)2755 napi_value NapiWebviewController::LoadUrl(napi_env env, napi_callback_info info)
2756 {
2757 napi_value thisVar = nullptr;
2758 napi_value result = nullptr;
2759 size_t argc = INTEGER_TWO;
2760 napi_value argv[INTEGER_TWO];
2761 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2762 if ((argc != INTEGER_ONE) && (argc != INTEGER_TWO)) {
2763 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2764 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "one", "two"));
2765 return nullptr;
2766 }
2767 WebviewController *webviewController = nullptr;
2768 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2769 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2770 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2771 return nullptr;
2772 }
2773 napi_valuetype webSrcType;
2774 napi_typeof(env, argv[INTEGER_ZERO], &webSrcType);
2775 if (webSrcType != napi_string && webSrcType != napi_object) {
2776 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2777 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_TYPE_INVALID, "url"));
2778 return nullptr;
2779 }
2780 std::string webSrc;
2781 if (!webviewController->ParseUrl(env, argv[INTEGER_ZERO], webSrc)) {
2782 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
2783 return nullptr;
2784 }
2785 if (argc == INTEGER_ONE) {
2786 ErrCode ret = webviewController->LoadUrl(webSrc);
2787 if (ret != NO_ERROR) {
2788 if (ret == NWEB_ERROR) {
2789 return nullptr;
2790 }
2791 BusinessError::ThrowErrorByErrcode(env, ret);
2792 return nullptr;
2793 }
2794 NAPI_CALL(env, napi_get_undefined(env, &result));
2795 return result;
2796 }
2797 return LoadUrlWithHttpHeaders(env, info, webSrc, argv, webviewController);
2798 }
2799
LoadUrlWithHttpHeaders(napi_env env,napi_callback_info info,const std::string & url,const napi_value * argv,WebviewController * webviewController)2800 napi_value NapiWebviewController::LoadUrlWithHttpHeaders(napi_env env, napi_callback_info info, const std::string& url,
2801 const napi_value* argv, WebviewController* webviewController)
2802 {
2803 napi_value result = nullptr;
2804 std::map<std::string, std::string> httpHeaders;
2805 napi_value array = argv[INTEGER_ONE];
2806 bool isArray = false;
2807 napi_is_array(env, array, &isArray);
2808 if (isArray) {
2809 uint32_t arrayLength = INTEGER_ZERO;
2810 napi_get_array_length(env, array, &arrayLength);
2811 for (uint32_t i = 0; i < arrayLength; ++i) {
2812 std::string key;
2813 std::string value;
2814 napi_value obj = nullptr;
2815 napi_value keyObj = nullptr;
2816 napi_value valueObj = nullptr;
2817 napi_get_element(env, array, i, &obj);
2818 if (napi_get_named_property(env, obj, "headerKey", &keyObj) != napi_ok) {
2819 continue;
2820 }
2821 if (napi_get_named_property(env, obj, "headerValue", &valueObj) != napi_ok) {
2822 continue;
2823 }
2824 NapiParseUtils::ParseString(env, keyObj, key);
2825 NapiParseUtils::ParseString(env, valueObj, value);
2826 httpHeaders[key] = value;
2827 }
2828 } else {
2829 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
2830 return nullptr;
2831 }
2832
2833 ErrCode ret = webviewController->LoadUrl(url, httpHeaders);
2834 if (ret != NO_ERROR) {
2835 if (ret == NWEB_ERROR) {
2836 WVLOG_E("LoadUrl failed.");
2837 return nullptr;
2838 }
2839 BusinessError::ThrowErrorByErrcode(env, ret);
2840 return nullptr;
2841 }
2842 NAPI_CALL(env, napi_get_undefined(env, &result));
2843 return result;
2844 }
2845
LoadData(napi_env env,napi_callback_info info)2846 napi_value NapiWebviewController::LoadData(napi_env env, napi_callback_info info)
2847 {
2848 napi_value thisVar = nullptr;
2849 napi_value result = nullptr;
2850 size_t argc = INTEGER_FIVE;
2851 napi_value argv[INTEGER_FIVE];
2852 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2853 if ((argc != INTEGER_THREE) && (argc != INTEGER_FOUR) &&
2854 (argc != INTEGER_FIVE)) {
2855 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2856 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "three", "four"));
2857 return nullptr;
2858 }
2859 WebviewController *webviewController = nullptr;
2860 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
2861 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
2862 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2863 return nullptr;
2864 }
2865 std::string data;
2866 std::string mimeType;
2867 std::string encoding;
2868 std::string baseUrl;
2869 std::string historyUrl;
2870 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], data) ||
2871 !NapiParseUtils::ParseString(env, argv[INTEGER_ONE], mimeType) ||
2872 !NapiParseUtils::ParseString(env, argv[INTEGER_TWO], encoding)) {
2873 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, ParamCheckErrorMsgTemplate::TYPE_ALL_STRING);
2874 return nullptr;
2875 }
2876 if ((argc >= INTEGER_FOUR) && !NapiParseUtils::ParseString(env, argv[INTEGER_THREE], baseUrl)) {
2877 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, ParamCheckErrorMsgTemplate::TYPE_ALL_STRING);
2878 return nullptr;
2879 }
2880 if ((argc == INTEGER_FIVE) && !NapiParseUtils::ParseString(env, argv[INTEGER_FOUR], historyUrl)) {
2881 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, ParamCheckErrorMsgTemplate::TYPE_ALL_STRING);
2882 return nullptr;
2883 }
2884 ErrCode ret = webviewController->LoadData(data, mimeType, encoding, baseUrl, historyUrl);
2885 if (ret != NO_ERROR) {
2886 if (ret == NWEB_ERROR) {
2887 WVLOG_E("LoadData failed.");
2888 return nullptr;
2889 }
2890 BusinessError::ThrowErrorByErrcode(env, ret);
2891 return nullptr;
2892 }
2893 NAPI_CALL(env, napi_get_undefined(env, &result));
2894 return result;
2895 }
2896
GetHitTest(napi_env env,napi_callback_info info)2897 napi_value NapiWebviewController::GetHitTest(napi_env env, napi_callback_info info)
2898 {
2899 napi_value result = nullptr;
2900 WebviewController *webviewController = GetWebviewController(env, info);
2901 if (!webviewController) {
2902 return nullptr;
2903 }
2904
2905 int32_t type = webviewController->GetHitTest();
2906 napi_create_int32(env, type, &result);
2907 return result;
2908 }
2909
ClearMatches(napi_env env,napi_callback_info info)2910 napi_value NapiWebviewController::ClearMatches(napi_env env, napi_callback_info info)
2911 {
2912 napi_value thisVar = nullptr;
2913 napi_value result = nullptr;
2914
2915 NAPI_CALL(env, napi_get_undefined(env, &result));
2916 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
2917
2918 WebviewController *controller = nullptr;
2919 napi_unwrap(env, thisVar, (void **)&controller);
2920 if (!controller || !controller->IsInit()) {
2921 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2922 return result;
2923 }
2924 controller->ClearMatches();
2925 return result;
2926 }
2927
SearchNext(napi_env env,napi_callback_info info)2928 napi_value NapiWebviewController::SearchNext(napi_env env, napi_callback_info info)
2929 {
2930 napi_value thisVar = nullptr;
2931 napi_value result = nullptr;
2932 size_t argc = INTEGER_ONE;
2933 napi_value argv[INTEGER_ONE] = { 0 };
2934
2935 NAPI_CALL(env, napi_get_undefined(env, &result));
2936 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2937 if (argc != INTEGER_ONE) {
2938 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2939 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2940 return result;
2941 }
2942 bool forward;
2943 if (!NapiParseUtils::ParseBoolean(env, argv[0], forward)) {
2944 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2945 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "forward", "boolean"));
2946 return result;
2947 }
2948
2949 WebviewController *controller = nullptr;
2950 napi_unwrap(env, thisVar, (void **)&controller);
2951 if (!controller || !controller->IsInit()) {
2952 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2953 return result;
2954 }
2955 controller->SearchNext(forward);
2956 return result;
2957 }
2958
SearchAllAsync(napi_env env,napi_callback_info info)2959 napi_value NapiWebviewController::SearchAllAsync(napi_env env, napi_callback_info info)
2960 {
2961 napi_value thisVar = nullptr;
2962 napi_value result = nullptr;
2963 size_t argc = INTEGER_ONE;
2964 napi_value argv[INTEGER_ONE] = { 0 };
2965
2966 NAPI_CALL(env, napi_get_undefined(env, &result));
2967 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
2968 if (argc != INTEGER_ONE) {
2969 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2970 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
2971 return result;
2972 }
2973 std::string searchString;
2974 if (!NapiParseUtils::ParseString(env, argv[0], searchString)) {
2975 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
2976 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "searchString", "number"));
2977 return result;
2978 }
2979
2980 WebviewController *controller = nullptr;
2981 napi_unwrap(env, thisVar, (void **)&controller);
2982 if (!controller || !controller->IsInit()) {
2983 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
2984 return result;
2985 }
2986 controller->SearchAllAsync(searchString);
2987 return result;
2988 }
2989
ClearSslCache(napi_env env,napi_callback_info info)2990 napi_value NapiWebviewController::ClearSslCache(napi_env env, napi_callback_info info)
2991 {
2992 napi_value thisVar = nullptr;
2993 napi_value result = nullptr;
2994
2995 NAPI_CALL(env, napi_get_undefined(env, &result));
2996 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
2997
2998 WebviewController *controller = nullptr;
2999 napi_unwrap(env, thisVar, (void **)&controller);
3000 if (!controller || !controller->IsInit()) {
3001 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3002 return result;
3003 }
3004 controller->ClearSslCache();
3005 return result;
3006 }
3007
ClearClientAuthenticationCache(napi_env env,napi_callback_info info)3008 napi_value NapiWebviewController::ClearClientAuthenticationCache(napi_env env, napi_callback_info info)
3009 {
3010 napi_value thisVar = nullptr;
3011 napi_value result = nullptr;
3012
3013 NAPI_CALL(env, napi_get_undefined(env, &result));
3014 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3015
3016 WebviewController *controller = nullptr;
3017 napi_unwrap(env, thisVar, (void **)&controller);
3018 if (!controller || !controller->IsInit()) {
3019 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3020 return result;
3021 }
3022 controller->ClearClientAuthenticationCache();
3023
3024 return result;
3025 }
3026
Stop(napi_env env,napi_callback_info info)3027 napi_value NapiWebviewController::Stop(napi_env env, napi_callback_info info)
3028 {
3029 napi_value thisVar = nullptr;
3030 napi_value result = nullptr;
3031 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3032
3033 WebviewController *controller = nullptr;
3034 napi_unwrap(env, thisVar, (void **)&controller);
3035 if (!controller || !controller->IsInit()) {
3036 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3037 return result;
3038 }
3039 controller->Stop();
3040
3041 NAPI_CALL(env, napi_get_undefined(env, &result));
3042 return result;
3043 }
3044
Zoom(napi_env env,napi_callback_info info)3045 napi_value NapiWebviewController::Zoom(napi_env env, napi_callback_info info)
3046 {
3047 napi_value thisVar = nullptr;
3048 napi_value result = nullptr;
3049 size_t argc = INTEGER_ONE;
3050 napi_value argv[INTEGER_ONE] = { 0 };
3051
3052 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3053 if (argc != INTEGER_ONE) {
3054 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3055 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3056 return result;
3057 }
3058 float factor = 0.0;
3059 if (!NapiParseUtils::ParseFloat(env, argv[0], factor)) {
3060 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3061 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "factor", "number"));
3062 return result;
3063 }
3064
3065 WebviewController *controller = nullptr;
3066 napi_unwrap(env, thisVar, (void **)&controller);
3067 if (!controller || !controller->IsInit()) {
3068 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3069 return result;
3070 }
3071
3072 ErrCode ret = controller->Zoom(factor);
3073 if (ret != NO_ERROR) {
3074 if (ret == NWEB_ERROR) {
3075 WVLOG_E("Zoom failed.");
3076 return result;
3077 }
3078 BusinessError::ThrowErrorByErrcode(env, ret);
3079 }
3080
3081 NAPI_CALL(env, napi_get_undefined(env, &result));
3082 return result;
3083 }
3084
InnerCompleteWindowNew(napi_env env,napi_callback_info info)3085 napi_value NapiWebviewController::InnerCompleteWindowNew(napi_env env, napi_callback_info info)
3086 {
3087 napi_value thisVar = nullptr;
3088 size_t argc = INTEGER_ONE;
3089 napi_value argv[INTEGER_ONE];
3090 void* data = nullptr;
3091 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
3092
3093 int32_t parentNwebId = -1;
3094 if (!NapiParseUtils::ParseInt32(env, argv[0], parentNwebId) || parentNwebId == -1) {
3095 WVLOG_E("Parse parent nweb id failed.");
3096 return nullptr;
3097 }
3098 WebviewController* webviewController = nullptr;
3099 napi_status status = napi_unwrap(env, thisVar, (void**)&webviewController);
3100 if ((!webviewController) || (status != napi_ok)) {
3101 WVLOG_E("webviewController is nullptr.");
3102 return nullptr;
3103 }
3104 webviewController->InnerCompleteWindowNew(parentNwebId);
3105 return thisVar;
3106 }
3107
RegisterJavaScriptProxy(napi_env env,napi_callback_info info)3108 napi_value NapiWebviewController::RegisterJavaScriptProxy(napi_env env, napi_callback_info info)
3109 {
3110 napi_value thisVar = nullptr;
3111 napi_value result = nullptr;
3112 size_t argc = INTEGER_FIVE;
3113 napi_value argv[INTEGER_FIVE] = { 0 };
3114 napi_get_undefined(env, &result);
3115 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3116 if (argc != INTEGER_THREE && argc != INTEGER_FOUR && argc != INTEGER_FIVE) {
3117 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3118 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_THREE, "three", "four", "five"));
3119 return result;
3120 }
3121 napi_valuetype valueType = napi_undefined;
3122 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
3123 if (valueType != napi_object) {
3124 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3125 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "object", "object"));
3126 return result;
3127 }
3128 RegisterJavaScriptProxyParam param;
3129 if (!ParseRegisterJavaScriptProxyParam(env, argc, argv, ¶m)) {
3130 return result;
3131 }
3132 WebviewController* controller = nullptr;
3133 napi_unwrap(env, thisVar, (void **)&controller);
3134 if (!controller || !controller->IsInit()) {
3135 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3136 return result;
3137 }
3138 controller->SetNWebJavaScriptResultCallBack();
3139 controller->RegisterJavaScriptProxy(param);
3140 return result;
3141 }
3142
DeleteJavaScriptRegister(napi_env env,napi_callback_info info)3143 napi_value NapiWebviewController::DeleteJavaScriptRegister(napi_env env, napi_callback_info info)
3144 {
3145 napi_value thisVar = nullptr;
3146 napi_value result = nullptr;
3147 size_t argc = INTEGER_ONE;
3148 napi_value argv[INTEGER_ONE] = { 0 };
3149
3150 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3151 if (argc != INTEGER_ONE) {
3152 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3153 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3154 return result;
3155 }
3156
3157 std::string objName;
3158 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], objName)) {
3159 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3160 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "name", "string"));
3161 return result;
3162 }
3163
3164 WebviewController *controller = nullptr;
3165 napi_unwrap(env, thisVar, (void **)&controller);
3166 if (!controller || !controller->IsInit()) {
3167 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3168 return result;
3169 }
3170 ErrCode ret = controller->DeleteJavaScriptRegister(objName, {});
3171 if (ret != NO_ERROR) {
3172 BusinessError::ThrowErrorByErrcode(env, ret);
3173 return result;
3174 }
3175
3176 NAPI_CALL(env, napi_get_undefined(env, &result));
3177 return result;
3178 }
3179
RunJavaScript(napi_env env,napi_callback_info info)3180 napi_value NapiWebviewController::RunJavaScript(napi_env env, napi_callback_info info)
3181 {
3182 return RunJS(env, info, false);
3183 }
3184
RunJavaScriptExt(napi_env env,napi_callback_info info)3185 napi_value NapiWebviewController::RunJavaScriptExt(napi_env env, napi_callback_info info)
3186 {
3187 return RunJS(env, info, true);
3188 }
3189
RunJS(napi_env env,napi_callback_info info,bool extention)3190 napi_value NapiWebviewController::RunJS(napi_env env, napi_callback_info info, bool extention)
3191 {
3192 napi_value thisVar = nullptr;
3193 napi_value result = nullptr;
3194 size_t argc = INTEGER_ONE;
3195 size_t argcPromise = INTEGER_ONE;
3196 size_t argcCallback = INTEGER_TWO;
3197 napi_value argv[INTEGER_TWO] = { 0 };
3198
3199 napi_get_undefined(env, &result);
3200 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3201
3202 if (argc != argcPromise && argc != argcCallback) {
3203 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3204 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
3205 return result;
3206 }
3207
3208 if (argc == argcCallback) {
3209 napi_valuetype valueType = napi_null;
3210 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3211 napi_typeof(env, argv[argcCallback - 1], &valueType);
3212 if (valueType != napi_function) {
3213 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3214 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "callback", "function"));
3215 return result;
3216 }
3217 }
3218
3219 if (maxFdNum_ == -1) {
3220 maxFdNum_ =
3221 std::atoi(NWebAdapterHelper::Instance().ParsePerfConfig("flowBufferConfig", "maxFdNumber").c_str());
3222 }
3223
3224 if (usedFd_.load() < maxFdNum_) {
3225 return RunJavaScriptInternalExt(env, info, extention);
3226 }
3227
3228 std::string script;
3229 napi_valuetype valueType = napi_undefined;
3230 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
3231 bool parseResult = (valueType == napi_string) ? NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], script) :
3232 NapiParseUtils::ParseArrayBuffer(env, argv[INTEGER_ZERO], script);
3233 if (!parseResult) {
3234 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3235 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "script", "string"));
3236 return result;
3237 }
3238 return RunJavaScriptInternal(env, info, script, extention);
3239 }
3240
RunJavaScriptInternal(napi_env env,napi_callback_info info,const std::string & script,bool extention)3241 napi_value NapiWebviewController::RunJavaScriptInternal(napi_env env, napi_callback_info info,
3242 const std::string &script, bool extention)
3243 {
3244 napi_value thisVar = nullptr;
3245 size_t argc = INTEGER_ONE;
3246 size_t argcPromise = INTEGER_ONE;
3247 size_t argcCallback = INTEGER_TWO;
3248 napi_value argv[INTEGER_TWO] = {0};
3249
3250 napi_value result = nullptr;
3251 napi_get_undefined(env, &result);
3252 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3253
3254 WebviewController *webviewController = nullptr;
3255 napi_unwrap(env, thisVar, (void **)&webviewController);
3256
3257 if (!webviewController || !webviewController->IsInit()) {
3258 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3259 return result;
3260 }
3261
3262 if (argc == argcCallback) {
3263 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3264 napi_ref jsCallback = nullptr;
3265 napi_create_reference(env, argv[argcCallback - 1], 1, &jsCallback);
3266
3267 if (jsCallback) {
3268 webviewController->RunJavaScriptCallback(script, env, std::move(jsCallback), extention);
3269 }
3270 return result;
3271 } else if (argc == argcPromise) {
3272 napi_deferred deferred = nullptr;
3273 napi_value promise = nullptr;
3274 napi_create_promise(env, &deferred, &promise);
3275 if (promise && deferred) {
3276 webviewController->RunJavaScriptPromise(script, env, deferred, extention);
3277 }
3278 return promise;
3279 }
3280 return result;
3281 }
3282
ConstructFlowbuf(napi_env env,napi_value argv,int & fd,size_t & scriptLength)3283 ErrCode NapiWebviewController::ConstructFlowbuf(napi_env env, napi_value argv, int& fd, size_t& scriptLength)
3284 {
3285 auto flowbufferAdapter = OhosAdapterHelper::GetInstance().CreateFlowbufferAdapter();
3286 if (!flowbufferAdapter) {
3287 return NWebError::NEW_OOM;
3288 }
3289 flowbufferAdapter->StartPerformanceBoost();
3290
3291 napi_valuetype valueType = napi_undefined;
3292 napi_typeof(env, argv, &valueType);
3293
3294 ErrCode constructResult = (valueType == napi_string) ?
3295 NapiParseUtils::ConstructStringFlowbuf(env, argv, fd, scriptLength) :
3296 NapiParseUtils::ConstructArrayBufFlowbuf(env, argv, fd, scriptLength);
3297 return constructResult;
3298 }
3299
RunJSBackToOriginal(napi_env env,napi_callback_info info,bool extention,napi_value argv,napi_value result)3300 napi_value NapiWebviewController::RunJSBackToOriginal(napi_env env, napi_callback_info info,
3301 bool extention, napi_value argv, napi_value result)
3302 {
3303 std::string script;
3304 napi_valuetype valueType = napi_undefined;
3305 napi_typeof(env, argv, &valueType);
3306 bool parseResult = (valueType == napi_string) ? NapiParseUtils::ParseString(env, argv, script) :
3307 NapiParseUtils::ParseArrayBuffer(env, argv, script);
3308 if (!parseResult) {
3309 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
3310 return result;
3311 }
3312 return RunJavaScriptInternal(env, info, script, extention);
3313 }
3314
RunJavaScriptInternalExt(napi_env env,napi_callback_info info,bool extention)3315 napi_value NapiWebviewController::RunJavaScriptInternalExt(napi_env env, napi_callback_info info, bool extention)
3316 {
3317 napi_value thisVar = nullptr;
3318 napi_value result = nullptr;
3319 size_t argc = INTEGER_ONE;
3320 size_t argcPromise = INTEGER_ONE;
3321 size_t argcCallback = INTEGER_TWO;
3322 napi_value argv[INTEGER_TWO] = {0};
3323
3324 napi_get_undefined(env, &result);
3325 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3326
3327 int fd;
3328 size_t scriptLength;
3329 ErrCode constructResult = ConstructFlowbuf(env, argv[INTEGER_ZERO], fd, scriptLength);
3330 if (constructResult != NO_ERROR) {
3331 return RunJSBackToOriginal(env, info, extention, argv[INTEGER_ZERO], result);
3332 }
3333 usedFd_++;
3334
3335 WebviewController *webviewController = nullptr;
3336 napi_unwrap(env, thisVar, (void **)&webviewController);
3337
3338 if (!webviewController || !webviewController->IsInit()) {
3339 close(fd);
3340 usedFd_--;
3341 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3342 return result;
3343 }
3344
3345 if (argc == argcCallback) {
3346 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3347 napi_ref jsCallback = nullptr;
3348 napi_create_reference(env, argv[argcCallback - 1], 1, &jsCallback);
3349
3350 if (jsCallback) {
3351 // RunJavaScriptCallbackExt will close fd after IPC
3352 webviewController->RunJavaScriptCallbackExt(fd, scriptLength, env, std::move(jsCallback), extention);
3353 }
3354 usedFd_--;
3355 return result;
3356 } else if (argc == argcPromise) {
3357 napi_deferred deferred = nullptr;
3358 napi_value promise = nullptr;
3359 napi_create_promise(env, &deferred, &promise);
3360 if (promise && deferred) {
3361 // RunJavaScriptCallbackExt will close fd after IPC
3362 webviewController->RunJavaScriptPromiseExt(fd, scriptLength, env, deferred, extention);
3363 }
3364 usedFd_--;
3365 return promise;
3366 }
3367 close(fd);
3368 usedFd_--;
3369 return result;
3370 }
3371
GetUrl(napi_env env,napi_callback_info info)3372 napi_value NapiWebviewController::GetUrl(napi_env env, napi_callback_info info)
3373 {
3374 napi_value result = nullptr;
3375 WebviewController *webviewController = GetWebviewController(env, info);
3376 if (!webviewController) {
3377 return nullptr;
3378 }
3379
3380 std::string url = "";
3381 url = webviewController->GetUrl();
3382 napi_create_string_utf8(env, url.c_str(), url.length(), &result);
3383
3384 return result;
3385 }
3386
GetOriginalUrl(napi_env env,napi_callback_info info)3387 napi_value NapiWebviewController::GetOriginalUrl(napi_env env, napi_callback_info info)
3388 {
3389 napi_value result = nullptr;
3390 WebviewController *webviewController = GetWebviewController(env, info);
3391 if (!webviewController) {
3392 return nullptr;
3393 }
3394
3395 std::string url = "";
3396 url = webviewController->GetOriginalUrl();
3397 napi_create_string_utf8(env, url.c_str(), url.length(), &result);
3398 return result;
3399 }
3400
TerminateRenderProcess(napi_env env,napi_callback_info info)3401 napi_value NapiWebviewController::TerminateRenderProcess(napi_env env, napi_callback_info info)
3402 {
3403 napi_value result = nullptr;
3404 WebviewController *webviewController = GetWebviewController(env, info);
3405 if (!webviewController) {
3406 return nullptr;
3407 }
3408 bool ret = false;
3409 ret = webviewController->TerminateRenderProcess();
3410 NAPI_CALL(env, napi_get_boolean(env, ret, &result));
3411 return result;
3412 }
3413
SetNetworkAvailable(napi_env env,napi_callback_info info)3414 napi_value NapiWebviewController::SetNetworkAvailable(napi_env env, napi_callback_info info)
3415 {
3416 napi_value thisVar = nullptr;
3417 napi_value result = nullptr;
3418 size_t argc = INTEGER_ONE;
3419 napi_value argv[INTEGER_ONE] = { 0 };
3420 bool enable;
3421
3422 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3423 if (argc != INTEGER_ONE) {
3424 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3425 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3426 return result;
3427 }
3428
3429 if (!NapiParseUtils::ParseBoolean(env, argv[0], enable)) {
3430 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3431 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "enable", "booleane"));
3432 return result;
3433 }
3434
3435 WebviewController *webviewController = nullptr;
3436 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
3437 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
3438 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3439 return nullptr;
3440 }
3441 webviewController->PutNetworkAvailable(enable);
3442 return result;
3443 }
3444
InnerGetWebId(napi_env env,napi_callback_info info)3445 napi_value NapiWebviewController::InnerGetWebId(napi_env env, napi_callback_info info)
3446 {
3447 napi_value thisVar = nullptr;
3448 napi_value result = nullptr;
3449 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3450
3451 WebviewController *webviewController = nullptr;
3452 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
3453 int32_t webId = -1;
3454 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
3455 WVLOG_E("Init error. The WebviewController must be associated with a Web component.");
3456 napi_create_int32(env, webId, &result);
3457 return result;
3458 }
3459
3460 webId = webviewController->GetWebId();
3461 napi_create_int32(env, webId, &result);
3462
3463 return result;
3464 }
3465
HasImage(napi_env env,napi_callback_info info)3466 napi_value NapiWebviewController::HasImage(napi_env env, napi_callback_info info)
3467 {
3468 napi_value thisVar = nullptr;
3469 napi_value result = nullptr;
3470 size_t argc = INTEGER_ONE;
3471 size_t argcPromiseParaNum = INTEGER_ZERO;
3472 size_t argcCallbackParaNum = INTEGER_ONE;
3473 napi_value argv[INTEGER_ONE] = { 0 };
3474
3475 napi_get_undefined(env, &result);
3476 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3477
3478 if (argc != argcPromiseParaNum && argc != argcCallbackParaNum) {
3479 NWebError::BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
3480 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "zero", "one"));
3481 return result;
3482 }
3483
3484 if (argc == argcCallbackParaNum) {
3485 napi_valuetype valueType = napi_null;
3486 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3487 napi_typeof(env, argv[argcCallbackParaNum - 1], &valueType);
3488 if (valueType != napi_function) {
3489 NWebError::BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
3490 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "callback", "function"));
3491 return result;
3492 }
3493 }
3494 return HasImageInternal(env, info);
3495 }
3496
HasImageInternal(napi_env env,napi_callback_info info)3497 napi_value NapiWebviewController::HasImageInternal(napi_env env, napi_callback_info info)
3498 {
3499 napi_value thisVar = nullptr;
3500 size_t argc = INTEGER_ONE;
3501 size_t argcPromiseParaNum = INTEGER_ZERO;
3502 size_t argcCallbackParaNum = INTEGER_ONE;
3503 napi_value argv[INTEGER_ONE] = { 0 };
3504
3505 napi_value result = nullptr;
3506 napi_get_undefined(env, &result);
3507 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3508
3509 WebviewController *webviewController = nullptr;
3510 napi_unwrap(env, thisVar, (void **)&webviewController);
3511
3512 if (!webviewController || !webviewController->IsInit()) {
3513 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3514 return result;
3515 }
3516
3517 if (argc == argcCallbackParaNum) {
3518 napi_ref jsCallback = nullptr;
3519 napi_create_reference(env, argv[argcCallbackParaNum - 1], 1, &jsCallback);
3520
3521 if (jsCallback) {
3522 ErrCode ret = webviewController->HasImagesCallback(env, std::move(jsCallback));
3523 if (ret == NWEB_ERROR) {
3524 return nullptr;
3525 } else if (ret != NO_ERROR) {
3526 BusinessError::ThrowErrorByErrcode(env, ret);
3527 return nullptr;
3528 }
3529 }
3530 return result;
3531 } else if (argc == argcPromiseParaNum) {
3532 napi_deferred deferred = nullptr;
3533 napi_value promise = nullptr;
3534 napi_create_promise(env, &deferred, &promise);
3535 if (promise && deferred) {
3536 ErrCode ret = webviewController->HasImagesPromise(env, deferred);
3537 if (ret == NWEB_ERROR) {
3538 return nullptr;
3539 } else if (ret != NO_ERROR) {
3540 BusinessError::ThrowErrorByErrcode(env, ret);
3541 return nullptr;
3542 }
3543 }
3544 return promise;
3545 }
3546 return result;
3547 }
3548
RemoveCache(napi_env env,napi_callback_info info)3549 napi_value NapiWebviewController::RemoveCache(napi_env env, napi_callback_info info)
3550 {
3551 napi_value thisVar = nullptr;
3552 napi_value result = nullptr;
3553 size_t argc = INTEGER_ONE;
3554 napi_value argv[INTEGER_ONE] = { 0 };
3555 bool includeDiskFiles;
3556
3557 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3558 if (argc != INTEGER_ONE) {
3559 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3560 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3561 return result;
3562 }
3563
3564 if (!NapiParseUtils::ParseBoolean(env, argv[0], includeDiskFiles)) {
3565 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3566 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "clearRom", "boolean"));
3567 return result;
3568 }
3569
3570 WebviewController *webviewController = nullptr;
3571 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
3572 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
3573 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3574 return nullptr;
3575 }
3576 webviewController->RemoveCache(includeDiskFiles);
3577 return result;
3578 }
3579
IsIncognitoMode(napi_env env,napi_callback_info info)3580 napi_value NapiWebviewController::IsIncognitoMode(napi_env env, napi_callback_info info)
3581 {
3582 napi_value result = nullptr;
3583 WebviewController *webviewController = GetWebviewController(env, info);
3584 if (!webviewController) {
3585 return nullptr;
3586 }
3587
3588 bool incognitoMode = false;
3589 incognitoMode = webviewController->IsIncognitoMode();
3590 NAPI_CALL(env, napi_get_boolean(env, incognitoMode, &result));
3591 return result;
3592 }
3593
JsConstructor(napi_env env,napi_callback_info info)3594 napi_value NapiWebHistoryList::JsConstructor(napi_env env, napi_callback_info info)
3595 {
3596 napi_value thisVar = nullptr;
3597 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3598 return thisVar;
3599 }
3600
getColorType(ImageColorType colorType)3601 Media::PixelFormat getColorType(ImageColorType colorType)
3602 {
3603 Media::PixelFormat pixelFormat_;
3604 switch (colorType) {
3605 case ImageColorType::COLOR_TYPE_UNKNOWN:
3606 pixelFormat_ = Media::PixelFormat::UNKNOWN;
3607 break;
3608 case ImageColorType::COLOR_TYPE_RGBA_8888:
3609 pixelFormat_ = Media::PixelFormat::RGBA_8888;
3610 break;
3611 case ImageColorType::COLOR_TYPE_BGRA_8888:
3612 pixelFormat_ = Media::PixelFormat::BGRA_8888;
3613 break;
3614 default:
3615 pixelFormat_ = Media::PixelFormat::UNKNOWN;
3616 break;
3617 }
3618 return pixelFormat_;
3619 }
3620
getAlphaType(ImageAlphaType alphaType)3621 Media::AlphaType getAlphaType(ImageAlphaType alphaType)
3622 {
3623 Media::AlphaType alphaType_;
3624 switch (alphaType) {
3625 case ImageAlphaType::ALPHA_TYPE_UNKNOWN:
3626 alphaType_ = Media::AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN;
3627 break;
3628 case ImageAlphaType::ALPHA_TYPE_OPAQUE:
3629 alphaType_ = Media::AlphaType::IMAGE_ALPHA_TYPE_OPAQUE;
3630 break;
3631 case ImageAlphaType::ALPHA_TYPE_PREMULTIPLIED:
3632 alphaType_ = Media::AlphaType::IMAGE_ALPHA_TYPE_PREMUL;
3633 break;
3634 case ImageAlphaType::ALPHA_TYPE_POSTMULTIPLIED:
3635 alphaType_ = Media::AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL;
3636 break;
3637 default:
3638 alphaType_ = Media::AlphaType::IMAGE_ALPHA_TYPE_UNKNOWN;
3639 break;
3640 }
3641 return alphaType_;
3642 }
3643
GetFavicon(napi_env env,std::shared_ptr<NWebHistoryItem> item)3644 napi_value NapiWebHistoryList::GetFavicon(napi_env env, std::shared_ptr<NWebHistoryItem> item)
3645 {
3646 napi_value result = nullptr;
3647 void *data = nullptr;
3648 int32_t width = 0;
3649 int32_t height = 0;
3650 ImageColorType colorType = ImageColorType::COLOR_TYPE_UNKNOWN;
3651 ImageAlphaType alphaType = ImageAlphaType::ALPHA_TYPE_UNKNOWN;
3652 bool isGetFavicon = item->GetFavicon(&data, width, height, colorType, alphaType);
3653 napi_get_null(env, &result);
3654
3655 if (!isGetFavicon) {
3656 return result;
3657 }
3658
3659 Media::InitializationOptions opt;
3660 opt.size.width = width;
3661 opt.size.height = height;
3662 opt.pixelFormat = getColorType(colorType);
3663 opt.alphaType = getAlphaType(alphaType);
3664 opt.editable = true;
3665 auto pixelMap = Media::PixelMap::Create(opt);
3666 if (pixelMap == nullptr) {
3667 return result;
3668 }
3669 uint64_t stride = static_cast<uint64_t>(width) << 2;
3670 uint64_t bufferSize = stride * static_cast<uint64_t>(height);
3671 pixelMap->WritePixels(static_cast<const uint8_t *>(data), bufferSize);
3672 std::shared_ptr<Media::PixelMap> pixelMapToJs(pixelMap.release());
3673 napi_value jsPixelMap = OHOS::Media::PixelMapNapi::CreatePixelMap(env, pixelMapToJs);
3674 return jsPixelMap;
3675 }
3676
GetItem(napi_env env,napi_callback_info info)3677 napi_value NapiWebHistoryList::GetItem(napi_env env, napi_callback_info info)
3678 {
3679 napi_value thisVar = nullptr;
3680 napi_value result = nullptr;
3681 size_t argc = INTEGER_ONE;
3682 napi_value argv[INTEGER_ONE] = { 0 };
3683 int32_t index;
3684 WebHistoryList *historyList = nullptr;
3685
3686 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
3687 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&historyList));
3688 if (historyList == nullptr) {
3689 WVLOG_E("unwrap historyList failed.");
3690 return result;
3691 }
3692 if (argc != INTEGER_ONE) {
3693 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3694 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3695 return result;
3696 }
3697 if (!NapiParseUtils::ParseInt32(env, argv[0], index)) {
3698 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3699 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NOT_NULL_TWO, "index", "int"));
3700 return result;
3701 }
3702 if (index >= historyList->GetListSize() || index < 0) {
3703 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3704 "BusinessError 401: Parameter error. The value of index must be greater than or equal to 0");
3705 return result;
3706 }
3707
3708 std::shared_ptr<NWebHistoryItem> item = historyList->GetItem(index);
3709 if (!item) {
3710 return result;
3711 }
3712
3713 napi_create_object(env, &result);
3714 std::string historyUrl = item->GetHistoryUrl();
3715 std::string historyRawUrl = item->GetHistoryRawUrl();
3716 std::string title = item->GetHistoryTitle();
3717
3718 napi_value js_historyUrl;
3719 napi_create_string_utf8(env, historyUrl.c_str(), historyUrl.length(), &js_historyUrl);
3720 napi_set_named_property(env, result, "historyUrl", js_historyUrl);
3721
3722 napi_value js_historyRawUrl;
3723 napi_create_string_utf8(env, historyRawUrl.c_str(), historyRawUrl.length(), &js_historyRawUrl);
3724 napi_set_named_property(env, result, "historyRawUrl", js_historyRawUrl);
3725
3726 napi_value js_title;
3727 napi_create_string_utf8(env, title.c_str(), title.length(), &js_title);
3728 napi_set_named_property(env, result, "title", js_title);
3729
3730 napi_value js_icon = GetFavicon(env, item);
3731 napi_set_named_property(env, result, "icon", js_icon);
3732 return result;
3733 }
3734
getBackForwardEntries(napi_env env,napi_callback_info info)3735 napi_value NapiWebviewController::getBackForwardEntries(napi_env env, napi_callback_info info)
3736 {
3737 napi_value thisVar = nullptr;
3738 napi_value result = nullptr;
3739 WebviewController *webviewController = nullptr;
3740
3741 NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr));
3742 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
3743 if (webviewController == nullptr || !webviewController->IsInit()) {
3744 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3745 return nullptr;
3746 }
3747
3748 std::shared_ptr<NWebHistoryList> list = webviewController->GetHistoryList();
3749 if (!list) {
3750 return result;
3751 }
3752
3753 int32_t currentIndex = list->GetCurrentIndex();
3754 int32_t size = list->GetListSize();
3755
3756 napi_value historyList = nullptr;
3757 NAPI_CALL(env, napi_get_reference_value(env, g_historyListRef, &historyList));
3758 NAPI_CALL(env, napi_new_instance(env, historyList, 0, NULL, &result));
3759
3760 napi_value js_currentIndex;
3761 napi_create_int32(env, currentIndex, &js_currentIndex);
3762 napi_set_named_property(env, result, "currentIndex", js_currentIndex);
3763
3764 napi_value js_size;
3765 napi_create_int32(env, size, &js_size);
3766 napi_set_named_property(env, result, "size", js_size);
3767
3768 WebHistoryList *webHistoryList = new (std::nothrow) WebHistoryList(list);
3769 if (webHistoryList == nullptr) {
3770 return result;
3771 }
3772
3773 NAPI_CALL(env, napi_wrap(env, result, webHistoryList,
3774 [](napi_env env, void *data, void *hint) {
3775 WebHistoryList *webHistoryList = static_cast<WebHistoryList *>(data);
3776 delete webHistoryList;
3777 },
3778 nullptr, nullptr));
3779
3780 return result;
3781 }
3782
GetFavicon(napi_env env,napi_callback_info info)3783 napi_value NapiWebviewController::GetFavicon(napi_env env, napi_callback_info info)
3784 {
3785 napi_value thisVar = nullptr;
3786 napi_value result = nullptr;
3787 napi_get_null(env, &result);
3788 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3789
3790 WebviewController *webviewController = nullptr;
3791 napi_unwrap(env, thisVar, (void **)&webviewController);
3792
3793 if (!webviewController || !webviewController->IsInit()) {
3794 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3795 return result;
3796 }
3797
3798 const void *data = nullptr;
3799 size_t width = 0;
3800 size_t height = 0;
3801 ImageColorType colorType = ImageColorType::COLOR_TYPE_UNKNOWN;
3802 ImageAlphaType alphaType = ImageAlphaType::ALPHA_TYPE_UNKNOWN;
3803 bool isGetFavicon = webviewController->GetFavicon(&data, width, height, colorType, alphaType);
3804 if (!isGetFavicon) {
3805 return result;
3806 }
3807
3808 Media::InitializationOptions opt;
3809 opt.size.width = static_cast<int32_t>(width);
3810 opt.size.height = static_cast<int32_t>(height);
3811 opt.pixelFormat = getColorType(colorType);
3812 opt.alphaType = getAlphaType(alphaType);
3813 opt.editable = true;
3814 auto pixelMap = Media::PixelMap::Create(opt);
3815 if (pixelMap == nullptr) {
3816 return result;
3817 }
3818 uint64_t stride = static_cast<uint64_t>(width) << 2;
3819 uint64_t bufferSize = stride * static_cast<uint64_t>(height);
3820 pixelMap->WritePixels(static_cast<const uint8_t *>(data), bufferSize);
3821 std::shared_ptr<Media::PixelMap> pixelMapToJs(pixelMap.release());
3822 napi_value jsPixelMap = OHOS::Media::PixelMapNapi::CreatePixelMap(env, pixelMapToJs);
3823 return jsPixelMap;
3824 }
3825
SerializeWebState(napi_env env,napi_callback_info info)3826 napi_value NapiWebviewController::SerializeWebState(napi_env env, napi_callback_info info)
3827 {
3828 napi_value thisVar = nullptr;
3829 napi_value result = nullptr;
3830 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3831 napi_get_null(env, &result);
3832
3833 WebviewController *webviewController = nullptr;
3834 napi_unwrap(env, thisVar, (void **)&webviewController);
3835 if (!webviewController || !webviewController->IsInit()) {
3836 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3837 return result;
3838 }
3839
3840 void *data = nullptr;
3841 napi_value buffer = nullptr;
3842 auto webState = webviewController->SerializeWebState();
3843
3844 NAPI_CALL(env, napi_create_arraybuffer(env, webState.size(), &data, &buffer));
3845 int retCode = memcpy_s(data, webState.size(), webState.data(), webState.size());
3846 if (retCode != 0) {
3847 return result;
3848 }
3849 NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, webState.size(), buffer, 0, &result));
3850 return result;
3851 }
3852
RestoreWebState(napi_env env,napi_callback_info info)3853 napi_value NapiWebviewController::RestoreWebState(napi_env env, napi_callback_info info)
3854 {
3855 napi_value thisVar = nullptr;
3856 napi_value result = nullptr;
3857 size_t argc = INTEGER_ONE;
3858 napi_value argv[INTEGER_ONE] = { 0 };
3859 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
3860 napi_get_null(env, &result);
3861
3862 WebviewController *webviewController = nullptr;
3863 napi_unwrap(env, thisVar, (void **)&webviewController);
3864 if (!webviewController || !webviewController->IsInit()) {
3865 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3866 return result;
3867 }
3868
3869 bool isTypedArray = false;
3870 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3871 if (argc != INTEGER_ONE) {
3872 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3873 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3874 return result;
3875 }
3876 NAPI_CALL(env, napi_is_typedarray(env, argv[0], &isTypedArray));
3877 if (!isTypedArray) {
3878 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3879 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "state", "uint8Array"));
3880 return result;
3881 }
3882
3883 napi_typedarray_type type;
3884 size_t length = 0;
3885 napi_value buffer = nullptr;
3886 size_t offset = 0;
3887 NAPI_CALL(env, napi_get_typedarray_info(env, argv[0], &type, &length, nullptr, &buffer, &offset));
3888 if (type != napi_uint8_array) {
3889 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3890 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "state", "uint8Array"));
3891 return result;
3892 }
3893 uint8_t *data = nullptr;
3894 size_t total = 0;
3895 NAPI_CALL(env, napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total));
3896 length = std::min<size_t>(length, total - offset);
3897 std::vector<uint8_t> state(length);
3898 int retCode = memcpy_s(state.data(), state.size(), &data[offset], length);
3899 if (retCode != 0) {
3900 return result;
3901 }
3902 webviewController->RestoreWebState(state);
3903 return result;
3904 }
3905
ScrollPageDown(napi_env env,napi_callback_info info)3906 napi_value NapiWebviewController::ScrollPageDown(napi_env env, napi_callback_info info)
3907 {
3908 napi_value thisVar = nullptr;
3909 napi_value result = nullptr;
3910 size_t argc = INTEGER_ONE;
3911 napi_value argv[INTEGER_ONE] = { 0 };
3912 bool bottom;
3913
3914 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3915 if (argc != INTEGER_ONE) {
3916 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3917 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3918 return result;
3919 }
3920
3921 if (!NapiParseUtils::ParseBoolean(env, argv[0], bottom)) {
3922 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3923 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "bottom", "booleane"));
3924 return result;
3925 }
3926
3927 WebviewController *webviewController = nullptr;
3928 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
3929 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
3930 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3931 return nullptr;
3932 }
3933 webviewController->ScrollPageDown(bottom);
3934 return result;
3935 }
3936
ScrollPageUp(napi_env env,napi_callback_info info)3937 napi_value NapiWebviewController::ScrollPageUp(napi_env env, napi_callback_info info)
3938 {
3939 napi_value thisVar = nullptr;
3940 napi_value result = nullptr;
3941 size_t argc = INTEGER_ONE;
3942 napi_value argv[INTEGER_ONE] = { 0 };
3943 bool top;
3944
3945 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
3946 if (argc != INTEGER_ONE) {
3947 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3948 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
3949 return result;
3950 }
3951
3952 if (!NapiParseUtils::ParseBoolean(env, argv[0], top)) {
3953 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
3954 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "top", "booleane"));
3955 return result;
3956 }
3957
3958 WebviewController *webviewController = nullptr;
3959 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
3960 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
3961 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
3962 return nullptr;
3963 }
3964 webviewController->ScrollPageUp(top);
3965 return result;
3966 }
3967
CheckSchemeName(const std::string & schemeName)3968 bool CheckSchemeName(const std::string& schemeName)
3969 {
3970 if (schemeName.empty() || schemeName.size() > MAX_CUSTOM_SCHEME_NAME_LENGTH) {
3971 WVLOG_E("Invalid scheme name length");
3972 return false;
3973 }
3974 for (auto it = schemeName.begin(); it != schemeName.end(); it++) {
3975 char chr = *it;
3976 if (!((chr >= 'a' && chr <= 'z') || (chr >= '0' && chr <= '9') ||
3977 (chr == '.') || (chr == '+') || (chr == '-'))) {
3978 WVLOG_E("invalid character %{public}c", chr);
3979 return false;
3980 }
3981 }
3982 return true;
3983 }
3984
SetCustomizeSchemeOption(Scheme & scheme)3985 void SetCustomizeSchemeOption(Scheme& scheme)
3986 {
3987 std::map<int, std::function<bool(const Scheme&)>> schemeProperties = {
3988 {0, [](const Scheme& scheme) { return scheme.isStandard; }},
3989 {1, [](const Scheme& scheme) { return scheme.isLocal; }},
3990 {2, [](const Scheme& scheme) { return scheme.isDisplayIsolated; }},
3991 {3, [](const Scheme& scheme) { return scheme.isSecure; }},
3992 {4, [](const Scheme& scheme) { return scheme.isSupportCORS; }},
3993 {5, [](const Scheme& scheme) { return scheme.isCspBypassing; }},
3994 {6, [](const Scheme& scheme) { return scheme.isSupportFetch; }},
3995 {7, [](const Scheme& scheme) { return scheme.isCodeCacheSupported; }}
3996 };
3997
3998 for (const auto& property : schemeProperties) {
3999 if (property.second(scheme)) {
4000 scheme.option += 1 << property.first;
4001 }
4002 }
4003 }
4004
SetCustomizeScheme(napi_env env,napi_value obj,Scheme & scheme)4005 bool SetCustomizeScheme(napi_env env, napi_value obj, Scheme& scheme)
4006 {
4007 std::map<std::string, std::function<void(Scheme&, bool)>> schemeBooleanProperties = {
4008 {"isSupportCORS", [](Scheme& scheme, bool value) { scheme.isSupportCORS = value; }},
4009 {"isSupportFetch", [](Scheme& scheme, bool value) { scheme.isSupportFetch = value; }},
4010 {"isStandard", [](Scheme& scheme, bool value) { scheme.isStandard = value; }},
4011 {"isLocal", [](Scheme& scheme, bool value) { scheme.isLocal = value; }},
4012 {"isDisplayIsolated", [](Scheme& scheme, bool value) { scheme.isDisplayIsolated = value; }},
4013 {"isSecure", [](Scheme& scheme, bool value) { scheme.isSecure = value; }},
4014 {"isCspBypassing", [](Scheme& scheme, bool value) { scheme.isCspBypassing = value; }},
4015 {"isCodeCacheSupported", [](Scheme& scheme, bool value) { scheme.isCodeCacheSupported = value; }}
4016 };
4017
4018 for (const auto& property : schemeBooleanProperties) {
4019 napi_value propertyObj = nullptr;
4020 napi_get_named_property(env, obj, property.first.c_str(), &propertyObj);
4021 bool schemeProperty = false;
4022 if (!NapiParseUtils::ParseBoolean(env, propertyObj, schemeProperty)) {
4023 if (property.first == "isSupportCORS" || property.first == "isSupportFetch") {
4024 return false;
4025 }
4026 }
4027 property.second(scheme, schemeProperty);
4028 }
4029
4030 napi_value schemeNameObj = nullptr;
4031 if (napi_get_named_property(env, obj, "schemeName", &schemeNameObj) != napi_ok) {
4032 return false;
4033 }
4034 if (!NapiParseUtils::ParseString(env, schemeNameObj, scheme.name)) {
4035 return false;
4036 }
4037
4038 if (!CheckSchemeName(scheme.name)) {
4039 return false;
4040 }
4041
4042 SetCustomizeSchemeOption(scheme);
4043 return true;
4044 }
4045
CustomizeSchemesArrayDataHandler(napi_env env,napi_value array)4046 int32_t CustomizeSchemesArrayDataHandler(napi_env env, napi_value array)
4047 {
4048 uint32_t arrayLength = 0;
4049 napi_get_array_length(env, array, &arrayLength);
4050 if (arrayLength > MAX_CUSTOM_SCHEME_SIZE) {
4051 return PARAM_CHECK_ERROR;
4052 }
4053 std::vector<Scheme> schemeVector;
4054 for (uint32_t i = 0; i < arrayLength; ++i) {
4055 napi_value obj = nullptr;
4056 napi_get_element(env, array, i, &obj);
4057 Scheme scheme;
4058 bool result = SetCustomizeScheme(env, obj, scheme);
4059 if (!result) {
4060 return PARAM_CHECK_ERROR;
4061 }
4062 schemeVector.push_back(scheme);
4063 }
4064 int32_t registerResult;
4065 for (auto it = schemeVector.begin(); it != schemeVector.end(); ++it) {
4066 registerResult = OH_ArkWeb_RegisterCustomSchemes(it->name.c_str(), it->option);
4067 if (registerResult != NO_ERROR) {
4068 return registerResult;
4069 }
4070 }
4071 return NO_ERROR;
4072 }
4073
CustomizeSchemes(napi_env env,napi_callback_info info)4074 napi_value NapiWebviewController::CustomizeSchemes(napi_env env, napi_callback_info info)
4075 {
4076 if (WebviewController::existNweb_) {
4077 WVLOG_E("There exist web component which has been already created.");
4078 }
4079
4080 napi_value result = nullptr;
4081 napi_value thisVar = nullptr;
4082 size_t argc = INTEGER_ONE;
4083 napi_value argv[INTEGER_ONE];
4084 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4085 if (argc != INTEGER_ONE) {
4086 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4087 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
4088 return nullptr;
4089 }
4090 napi_value array = argv[INTEGER_ZERO];
4091 bool isArray = false;
4092 napi_is_array(env, array, &isArray);
4093 if (!isArray) {
4094 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4095 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "schemes", "array"));
4096 return nullptr;
4097 }
4098 int32_t registerResult = CustomizeSchemesArrayDataHandler(env, array);
4099 if (registerResult == NO_ERROR) {
4100 NAPI_CALL(env, napi_get_undefined(env, &result));
4101 return result;
4102 }
4103 if (registerResult == PARAM_CHECK_ERROR) {
4104 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4105 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "schemeName", "string"));
4106 return nullptr;
4107 }
4108 BusinessError::ThrowErrorByErrcode(env, REGISTER_CUSTOM_SCHEME_FAILED);
4109 return nullptr;
4110 }
4111
ScrollTo(napi_env env,napi_callback_info info)4112 napi_value NapiWebviewController::ScrollTo(napi_env env, napi_callback_info info)
4113 {
4114 napi_value thisVar = nullptr;
4115 napi_value result = nullptr;
4116 size_t argc = INTEGER_TWO;
4117 napi_value argv[INTEGER_TWO] = { 0 };
4118 float x;
4119 float y;
4120
4121 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4122 if (argc != INTEGER_TWO) {
4123 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4124 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
4125 return result;
4126 }
4127
4128 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ZERO], x)) {
4129 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4130 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "x", "number"));
4131 return result;
4132 }
4133
4134 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ONE], y)) {
4135 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4136 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "y", "number"));
4137 return result;
4138 }
4139
4140 WebviewController *webviewController = nullptr;
4141 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
4142 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4143 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4144 return nullptr;
4145 }
4146 webviewController->ScrollTo(x, y);
4147 return result;
4148 }
4149
ScrollBy(napi_env env,napi_callback_info info)4150 napi_value NapiWebviewController::ScrollBy(napi_env env, napi_callback_info info)
4151 {
4152 napi_value thisVar = nullptr;
4153 napi_value result = nullptr;
4154 size_t argc = INTEGER_TWO;
4155 napi_value argv[INTEGER_TWO] = { 0 };
4156 float deltaX;
4157 float deltaY;
4158
4159 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4160 if (argc != INTEGER_TWO) {
4161 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4162 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
4163 return result;
4164 }
4165
4166 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ZERO], deltaX)) {
4167 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4168 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaX", "number"));
4169 return result;
4170 }
4171
4172 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ONE], deltaY)) {
4173 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4174 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaY", "number"));
4175 return result;
4176 }
4177
4178 WebviewController *webviewController = nullptr;
4179 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
4180 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4181 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4182 return nullptr;
4183 }
4184 webviewController->ScrollBy(deltaX, deltaY);
4185 return result;
4186 }
4187
SlideScroll(napi_env env,napi_callback_info info)4188 napi_value NapiWebviewController::SlideScroll(napi_env env, napi_callback_info info)
4189 {
4190 napi_value thisVar = nullptr;
4191 napi_value result = nullptr;
4192 size_t argc = INTEGER_TWO;
4193 napi_value argv[INTEGER_TWO] = { 0 };
4194 float vx;
4195 float vy;
4196
4197 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4198 if (argc != INTEGER_TWO) {
4199 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4200 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
4201 return result;
4202 }
4203
4204 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ZERO], vx)) {
4205 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4206 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "vx", "number"));
4207 return result;
4208 }
4209
4210 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ONE], vy)) {
4211 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4212 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "vy", "number"));
4213 return result;
4214 }
4215
4216 WebviewController *webviewController = nullptr;
4217 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
4218 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4219 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4220 return nullptr;
4221 }
4222 webviewController->SlideScroll(vx, vy);
4223 return result;
4224 }
4225
SetScrollable(napi_env env,napi_callback_info info)4226 napi_value NapiWebviewController::SetScrollable(napi_env env, napi_callback_info info)
4227 {
4228 napi_value thisVar = nullptr;
4229 napi_value result = nullptr;
4230 size_t argc = INTEGER_TWO;
4231 size_t argcForOld = INTEGER_ONE;
4232 napi_value argv[INTEGER_TWO] = { 0 };
4233
4234 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4235 if (argc != INTEGER_TWO && argc != argcForOld) {
4236 NWebError::BusinessError::ThrowErrorByErrcode(env, NWebError::PARAM_CHECK_ERROR,
4237 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_TWO, "one", "two"));
4238 return result;
4239 }
4240 bool isEnableScroll;
4241 if (!NapiParseUtils::ParseBoolean(env, argv[0], isEnableScroll)) {
4242 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4243 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "enable", "boolean"));
4244 return result;
4245 }
4246
4247 int32_t scrollType = -1;
4248 if (argc == INTEGER_TWO) {
4249 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ONE], scrollType) || scrollType < 0 ||
4250 scrollType >= INTEGER_ONE) {
4251 WVLOG_E("BusinessError: 401. The character of 'scrollType' must be int32.");
4252 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4253 return result;
4254 }
4255 }
4256
4257 WebviewController* webviewController = nullptr;
4258 napi_status status = napi_unwrap(env, thisVar, (void**)&webviewController);
4259 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4260 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4261 return nullptr;
4262 }
4263 webviewController->SetScrollable(isEnableScroll, scrollType);
4264 return result;
4265 }
4266
GetScrollable(napi_env env,napi_callback_info info)4267 napi_value NapiWebviewController::GetScrollable(napi_env env, napi_callback_info info)
4268 {
4269 napi_value result = nullptr;
4270 WebviewController *webviewController = GetWebviewController(env, info);
4271 if (!webviewController) {
4272 return nullptr;
4273 }
4274
4275 bool isScrollable = webviewController->GetScrollable();
4276 NAPI_CALL(env, napi_get_boolean(env, isScrollable, &result));
4277 return result;
4278 }
4279
InnerGetCertificate(napi_env env,napi_callback_info info)4280 napi_value NapiWebviewController::InnerGetCertificate(napi_env env, napi_callback_info info)
4281 {
4282 napi_value thisVar = nullptr;
4283 napi_value result = nullptr;
4284 napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
4285 napi_create_array(env, &result);
4286
4287 WebviewController *webviewController = nullptr;
4288 napi_unwrap(env, thisVar, (void **)&webviewController);
4289 if (!webviewController || !webviewController->IsInit()) {
4290 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4291 return result;
4292 }
4293
4294 std::vector<std::string> certChainDerData;
4295 bool ans = webviewController->GetCertChainDerData(certChainDerData);
4296 if (!ans) {
4297 WVLOG_E("get cert chain data failed");
4298 return result;
4299 }
4300
4301 for (uint8_t i = 0; i < certChainDerData.size(); i++) {
4302 if (i == UINT8_MAX) {
4303 WVLOG_E("error, cert chain data array reach max");
4304 break;
4305 }
4306 void *data = nullptr;
4307 napi_value buffer = nullptr;
4308 napi_value item = nullptr;
4309 NAPI_CALL(env, napi_create_arraybuffer(env, certChainDerData[i].size(), &data, &buffer));
4310 int retCode = memcpy_s(data, certChainDerData[i].size(),
4311 certChainDerData[i].data(), certChainDerData[i].size());
4312 if (retCode != 0) {
4313 WVLOG_E("memcpy_s cert data failed, index = %{public}u,", i);
4314 continue;
4315 }
4316 NAPI_CALL(env, napi_create_typedarray(env, napi_uint8_array, certChainDerData[i].size(), buffer, 0, &item));
4317 NAPI_CALL(env, napi_set_element(env, result, i, item));
4318 }
4319 return result;
4320 }
4321
SetAudioMuted(napi_env env,napi_callback_info info)4322 napi_value NapiWebviewController::SetAudioMuted(napi_env env, napi_callback_info info)
4323 {
4324 WVLOG_D("SetAudioMuted invoked");
4325
4326 napi_value result = nullptr;
4327 NAPI_CALL(env, napi_get_undefined(env, &result));
4328
4329 napi_value thisVar = nullptr;
4330 size_t argc = INTEGER_ONE;
4331 napi_value argv[INTEGER_ONE] = { 0 };
4332 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4333 if (argc != INTEGER_ONE) {
4334 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4335 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
4336 return result;
4337 }
4338
4339 bool muted = false;
4340 if (!NapiParseUtils::ParseBoolean(env, argv[0], muted)) {
4341 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4342 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "mute", "boolean"));
4343 return result;
4344 }
4345
4346 WebviewController* webviewController = nullptr;
4347 napi_status status = napi_unwrap(env, thisVar, (void**)&webviewController);
4348 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4349 WVLOG_E("SetAudioMuted failed due to no associated Web component");
4350 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4351 return result;
4352 }
4353
4354 ErrCode ret = webviewController->SetAudioMuted(muted);
4355 if (ret != NO_ERROR) {
4356 WVLOG_E("SetAudioMuted failed, error code: %{public}d", ret);
4357 BusinessError::ThrowErrorByErrcode(env, ret);
4358 return result;
4359 }
4360
4361 WVLOG_I("SetAudioMuted: %{public}s", (muted ? "true" : "false"));
4362 return result;
4363 }
4364
PrefetchPage(napi_env env,napi_callback_info info)4365 napi_value NapiWebviewController::PrefetchPage(napi_env env, napi_callback_info info)
4366 {
4367 napi_value thisVar = nullptr;
4368 napi_value result = nullptr;
4369 size_t argc = INTEGER_TWO;
4370 napi_value argv[INTEGER_TWO];
4371 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4372 WebviewController *webviewController = nullptr;
4373 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
4374 if ((argc != INTEGER_ONE) && (argc != INTEGER_TWO)) {
4375 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4376 return nullptr;
4377 }
4378 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4379 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4380 return nullptr;
4381 }
4382 std::string url;
4383 if (!ParsePrepareUrl(env, argv[INTEGER_ZERO], url)) {
4384 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
4385 return nullptr;
4386 }
4387 std::map<std::string, std::string> additionalHttpHeaders;
4388 if (argc == INTEGER_ONE) {
4389 ErrCode ret = webviewController->PrefetchPage(url, additionalHttpHeaders);
4390 if (ret != NO_ERROR) {
4391 WVLOG_E("PrefetchPage failed, error code: %{public}d", ret);
4392 BusinessError::ThrowErrorByErrcode(env, ret);
4393 return nullptr;
4394 }
4395 NAPI_CALL(env, napi_get_undefined(env, &result));
4396 return result;
4397 }
4398 return PrefetchPageWithHttpHeaders(env, info, url, argv, webviewController);
4399 }
4400
PrefetchPageWithHttpHeaders(napi_env env,napi_callback_info info,std::string & url,const napi_value * argv,WebviewController * webviewController)4401 napi_value NapiWebviewController::PrefetchPageWithHttpHeaders(napi_env env, napi_callback_info info, std::string& url,
4402 const napi_value* argv, WebviewController* webviewController)
4403 {
4404 napi_value result = nullptr;
4405 std::map<std::string, std::string> additionalHttpHeaders;
4406 napi_value array = argv[INTEGER_ONE];
4407 bool isArray = false;
4408 napi_is_array(env, array, &isArray);
4409 if (isArray) {
4410 uint32_t arrayLength = INTEGER_ZERO;
4411 napi_get_array_length(env, array, &arrayLength);
4412 for (uint32_t i = 0; i < arrayLength; ++i) {
4413 std::string key;
4414 std::string value;
4415 napi_value obj = nullptr;
4416 napi_value keyObj = nullptr;
4417 napi_value valueObj = nullptr;
4418 napi_get_element(env, array, i, &obj);
4419 if (napi_get_named_property(env, obj, "headerKey", &keyObj) != napi_ok) {
4420 continue;
4421 }
4422 if (napi_get_named_property(env, obj, "headerValue", &valueObj) != napi_ok) {
4423 continue;
4424 }
4425 NapiParseUtils::ParseString(env, keyObj, key);
4426 NapiParseUtils::ParseString(env, valueObj, value);
4427 additionalHttpHeaders[key] = value;
4428 }
4429 } else {
4430 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4431 return nullptr;
4432 }
4433
4434 ErrCode ret = webviewController->PrefetchPage(url, additionalHttpHeaders);
4435 if (ret != NO_ERROR) {
4436 WVLOG_E("PrefetchPage failed, error code: %{public}d", ret);
4437 BusinessError::ThrowErrorByErrcode(env, ret);
4438 return nullptr;
4439 }
4440 NAPI_CALL(env, napi_get_undefined(env, &result));
4441 return result;
4442 }
4443
GetLastJavascriptProxyCallingFrameUrl(napi_env env,napi_callback_info info)4444 napi_value NapiWebviewController::GetLastJavascriptProxyCallingFrameUrl(napi_env env, napi_callback_info info)
4445 {
4446 napi_value result = nullptr;
4447 WebviewController *webviewController = GetWebviewController(env, info);
4448 if (!webviewController) {
4449 return nullptr;
4450 }
4451
4452 std::string lastCallingFrameUrl = webviewController->GetLastJavascriptProxyCallingFrameUrl();
4453 napi_create_string_utf8(env, lastCallingFrameUrl.c_str(), lastCallingFrameUrl.length(), &result);
4454 return result;
4455 }
4456
PrepareForPageLoad(napi_env env,napi_callback_info info)4457 napi_value NapiWebviewController::PrepareForPageLoad(napi_env env, napi_callback_info info)
4458 {
4459 napi_value thisVar = nullptr;
4460 napi_value result = nullptr;
4461 size_t argc = INTEGER_THREE;
4462 napi_value argv[INTEGER_THREE] = { 0 };
4463 napi_get_undefined(env, &result);
4464 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4465 if (argc != INTEGER_THREE) {
4466 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4467 return nullptr;
4468 }
4469
4470 std::string url;
4471 if (!ParsePrepareUrl(env, argv[INTEGER_ZERO], url)) {
4472 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
4473 return nullptr;
4474 }
4475
4476 bool preconnectable = false;
4477 if (!NapiParseUtils::ParseBoolean(env, argv[INTEGER_ONE], preconnectable)) {
4478 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4479 return nullptr;
4480 }
4481
4482 int32_t numSockets = 0;
4483 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_TWO], numSockets)) {
4484 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4485 return nullptr;
4486 }
4487 if (numSockets <= 0 || static_cast<uint32_t>(numSockets) > SOCKET_MAXIMUM) {
4488 BusinessError::ThrowErrorByErrcode(env, INVALID_SOCKET_NUMBER);
4489 return nullptr;
4490 }
4491
4492 NWebHelper::Instance().PrepareForPageLoad(url, preconnectable, numSockets);
4493 NAPI_CALL(env, napi_get_undefined(env, &result));
4494 return result;
4495 }
4496
PrefetchResource(napi_env env,napi_callback_info info)4497 napi_value NapiWebviewController::PrefetchResource(napi_env env, napi_callback_info info)
4498 {
4499 napi_value thisVar = nullptr;
4500 napi_value result = nullptr;
4501 size_t argc = INTEGER_FOUR;
4502 napi_value argv[INTEGER_FOUR] = { 0 };
4503 napi_get_undefined(env, &result);
4504 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4505 if (argc > INTEGER_FOUR || argc < INTEGER_ONE) {
4506 WVLOG_E("BusinessError: 401. Arg count must between 1 and 4.");
4507 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4508 return nullptr;
4509 }
4510
4511 std::shared_ptr<NWebEnginePrefetchArgs> prefetchArgs = ParsePrefetchArgs(env, argv[INTEGER_ZERO]);
4512 if (prefetchArgs == nullptr) {
4513 return nullptr;
4514 }
4515
4516 std::map<std::string, std::string> additionalHttpHeaders;
4517 if (argc >= INTEGER_TWO && !ParseHttpHeaders(env, argv[INTEGER_ONE], &additionalHttpHeaders)) {
4518 WVLOG_E("BusinessError: 401. The type of 'additionalHttpHeaders' must be Array of 'WebHeader'.");
4519 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4520 return nullptr;
4521 }
4522
4523 std::string cacheKey;
4524 if ((argc >= INTEGER_THREE) && !NapiParseUtils::ParseString(env, argv[INTEGER_TWO], cacheKey)) {
4525 WVLOG_E("BusinessError: 401.The type of 'cacheKey' must be string.");
4526 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4527 return nullptr;
4528 }
4529
4530 if (cacheKey.empty()) {
4531 cacheKey = prefetchArgs->GetUrl();
4532 } else {
4533 if (!CheckCacheKey(env, cacheKey)) {
4534 return nullptr;
4535 }
4536 }
4537
4538 int32_t cacheValidTime = 0;
4539 if (argc >= INTEGER_FOUR) {
4540 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_THREE], cacheValidTime) || cacheValidTime <= 0 ||
4541 cacheValidTime > INT_MAX) {
4542 WVLOG_E("BusinessError: 401. The character of 'cacheValidTime' must be int32.");
4543 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4544 return nullptr;
4545 }
4546 }
4547
4548 NAPI_CALL(env, napi_get_undefined(env, &result));
4549 NWebHelper::Instance().PrefetchResource(prefetchArgs, additionalHttpHeaders, cacheKey, cacheValidTime);
4550 return result;
4551 }
4552
CloseAllMediaPresentations(napi_env env,napi_callback_info info)4553 napi_value NapiWebviewController::CloseAllMediaPresentations(napi_env env, napi_callback_info info)
4554 {
4555 napi_value result = nullptr;
4556 WebviewController* webviewController = GetWebviewController(env, info);
4557 if (!webviewController) {
4558 return result;
4559 }
4560
4561 webviewController->CloseAllMediaPresentations();
4562 NAPI_CALL(env, napi_get_undefined(env, &result));
4563 return result;
4564 }
4565
StopAllMedia(napi_env env,napi_callback_info info)4566 napi_value NapiWebviewController::StopAllMedia(napi_env env, napi_callback_info info)
4567 {
4568 napi_value result = nullptr;
4569 WebviewController* webviewController = GetWebviewController(env, info);
4570 if (!webviewController) {
4571 return result;
4572 }
4573
4574 webviewController->StopAllMedia();
4575 NAPI_CALL(env, napi_get_undefined(env, &result));
4576 return result;
4577 }
4578
ResumeAllMedia(napi_env env,napi_callback_info info)4579 napi_value NapiWebviewController::ResumeAllMedia(napi_env env, napi_callback_info info)
4580 {
4581 napi_value result = nullptr;
4582 WebviewController* webviewController = GetWebviewController(env, info);
4583 if (!webviewController) {
4584 return result;
4585 }
4586
4587 webviewController->ResumeAllMedia();
4588 NAPI_CALL(env, napi_get_undefined(env, &result));
4589 return result;
4590 }
4591
PauseAllMedia(napi_env env,napi_callback_info info)4592 napi_value NapiWebviewController::PauseAllMedia(napi_env env, napi_callback_info info)
4593 {
4594 napi_value result = nullptr;
4595 WebviewController* webviewController = GetWebviewController(env, info);
4596 if (!webviewController) {
4597 return result;
4598 }
4599
4600 webviewController->PauseAllMedia();
4601 NAPI_CALL(env, napi_get_undefined(env, &result));
4602 return result;
4603 }
4604
GetMediaPlaybackState(napi_env env,napi_callback_info info)4605 napi_value NapiWebviewController::GetMediaPlaybackState(napi_env env, napi_callback_info info)
4606 {
4607 napi_value result = nullptr;
4608 WebviewController* webviewController = GetWebviewController(env, info);
4609 if (!webviewController) {
4610 return result;
4611 }
4612
4613 int32_t mediaPlaybackState = webviewController->GetMediaPlaybackState();
4614 napi_create_int32(env, mediaPlaybackState, &result);
4615 return result;
4616 }
4617
ClearPrefetchedResource(napi_env env,napi_callback_info info)4618 napi_value NapiWebviewController::ClearPrefetchedResource(napi_env env, napi_callback_info info)
4619 {
4620 napi_value thisVar = nullptr;
4621 napi_value result = nullptr;
4622 size_t argc = INTEGER_ONE;
4623 napi_value argv[INTEGER_ONE] = { 0 };
4624 napi_get_undefined(env, &result);
4625 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4626 if (argc != INTEGER_ONE) {
4627 WVLOG_E("BusinessError: 401. Arg count must be 1.");
4628 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4629 return nullptr;
4630 }
4631
4632 std::vector<std::string> cacheKeyList;
4633 if (!ParseCacheKeyList(env, argv[INTEGER_ZERO], &cacheKeyList)) {
4634 WVLOG_E("BusinessError: 401. The type of 'cacheKeyList' must be Array of string.");
4635 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4636 return nullptr;
4637 }
4638
4639 NAPI_CALL(env, napi_get_undefined(env, &result));
4640 NWebHelper::Instance().ClearPrefetchedResource(cacheKeyList);
4641 return result;
4642 }
4643
CreateWebPrintDocumentAdapter(napi_env env,napi_callback_info info)4644 napi_value NapiWebviewController::CreateWebPrintDocumentAdapter(napi_env env, napi_callback_info info)
4645 {
4646 WVLOG_I("Create web print document adapter.");
4647 napi_value thisVar = nullptr;
4648 napi_value result = nullptr;
4649 size_t argc = INTEGER_ONE;
4650 napi_value argv[INTEGER_ONE];
4651 NAPI_CALL(env, napi_get_undefined(env, &result));
4652 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4653 if (argc != INTEGER_ONE) {
4654 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4655 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
4656 return result;
4657 }
4658
4659 std::string jobName;
4660 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], jobName)) {
4661 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
4662 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "jopName", "string"));
4663 return result;
4664 }
4665
4666 WebviewController *webviewController = nullptr;
4667 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
4668 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
4669 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
4670 return result;
4671 }
4672 void* webPrintDocument = webviewController->CreateWebPrintDocumentAdapter(jobName);
4673 if (!webPrintDocument) {
4674 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4675 return result;
4676 }
4677
4678 napi_value webPrintDoc = nullptr;
4679 NAPI_CALL(env, napi_get_reference_value(env, g_webPrintDocClassRef, &webPrintDoc));
4680 napi_value consParam[INTEGER_ONE] = {0};
4681 NAPI_CALL(env, napi_create_bigint_uint64(env, reinterpret_cast<uint64_t>(webPrintDocument),
4682 &consParam[INTEGER_ZERO]));
4683 napi_value proxy = nullptr;
4684 status = napi_new_instance(env, webPrintDoc, INTEGER_ONE, &consParam[INTEGER_ZERO], &proxy);
4685 if (status!= napi_ok) {
4686 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4687 return result;
4688 }
4689 return proxy;
4690 }
4691
GetSecurityLevel(napi_env env,napi_callback_info info)4692 napi_value NapiWebviewController::GetSecurityLevel(napi_env env, napi_callback_info info)
4693 {
4694 napi_value result = nullptr;
4695 WebviewController *webviewController = GetWebviewController(env, info);
4696 if (!webviewController) {
4697 return result;
4698 }
4699
4700 int32_t securityLevel = webviewController->GetSecurityLevel();
4701 napi_create_int32(env, securityLevel, &result);
4702 return result;
4703 }
4704
ParsePrintRangeAdapter(napi_env env,napi_value pageRange,PrintAttributesAdapter & printAttr)4705 void ParsePrintRangeAdapter(napi_env env, napi_value pageRange, PrintAttributesAdapter& printAttr)
4706 {
4707 if (!pageRange) {
4708 WVLOG_E("ParsePrintRangeAdapter failed.");
4709 return;
4710 }
4711 napi_value startPage = nullptr;
4712 napi_value endPage = nullptr;
4713 napi_value pages = nullptr;
4714 napi_get_named_property(env, pageRange, "startPage", &startPage);
4715 napi_get_named_property(env, pageRange, "endPage", &endPage);
4716 if (startPage) {
4717 NapiParseUtils::ParseUint32(env, startPage, printAttr.pageRange.startPage);
4718 }
4719 if (endPage) {
4720 NapiParseUtils::ParseUint32(env, endPage, printAttr.pageRange.endPage);
4721 }
4722 napi_get_named_property(env, pageRange, "pages", &pages);
4723 uint32_t pageArrayLength = 0;
4724 napi_get_array_length(env, pages, &pageArrayLength);
4725 for (uint32_t i = 0; i < pageArrayLength; ++i) {
4726 napi_value pagesNumObj = nullptr;
4727 napi_get_element(env, pages, i, &pagesNumObj);
4728 uint32_t pagesNum;
4729 NapiParseUtils::ParseUint32(env, pagesNumObj, pagesNum);
4730 printAttr.pageRange.pages.push_back(pagesNum);
4731 }
4732 }
4733
ParsePrintPageSizeAdapter(napi_env env,napi_value pageSize,PrintAttributesAdapter & printAttr)4734 void ParsePrintPageSizeAdapter(napi_env env, napi_value pageSize, PrintAttributesAdapter& printAttr)
4735 {
4736 if (!pageSize) {
4737 WVLOG_E("ParsePrintPageSizeAdapter failed.");
4738 return;
4739 }
4740 napi_value id = nullptr;
4741 napi_value name = nullptr;
4742 napi_value width = nullptr;
4743 napi_value height = nullptr;
4744 napi_get_named_property(env, pageSize, "id", &id);
4745 napi_get_named_property(env, pageSize, "name", &name);
4746 napi_get_named_property(env, pageSize, "width", &width);
4747 napi_get_named_property(env, pageSize, "height", &height);
4748 if (width) {
4749 NapiParseUtils::ParseUint32(env, width, printAttr.pageSize.width);
4750 }
4751 if (height) {
4752 NapiParseUtils::ParseUint32(env, height, printAttr.pageSize.height);
4753 }
4754 }
4755
ParsePrintMarginAdapter(napi_env env,napi_value margin,PrintAttributesAdapter & printAttr)4756 void ParsePrintMarginAdapter(napi_env env, napi_value margin, PrintAttributesAdapter& printAttr)
4757 {
4758 if (!margin) {
4759 WVLOG_E("ParsePrintMarginAdapter failed.");
4760 return;
4761 }
4762 napi_value top = nullptr;
4763 napi_value bottom = nullptr;
4764 napi_value left = nullptr;
4765 napi_value right = nullptr;
4766 napi_get_named_property(env, margin, "top", &top);
4767 napi_get_named_property(env, margin, "bottom", &bottom);
4768 napi_get_named_property(env, margin, "left", &left);
4769 napi_get_named_property(env, margin, "right", &right);
4770 if (top) {
4771 NapiParseUtils::ParseUint32(env, top, printAttr.margin.top);
4772 }
4773 if (bottom) {
4774 NapiParseUtils::ParseUint32(env, bottom, printAttr.margin.bottom);
4775 }
4776 if (left) {
4777 NapiParseUtils::ParseUint32(env, left, printAttr.margin.left);
4778 }
4779 if (right) {
4780 NapiParseUtils::ParseUint32(env, right, printAttr.margin.right);
4781 }
4782 }
4783
ParseWebPrintWriteResultCallback(napi_env env,napi_value argv)4784 WebPrintWriteResultCallback ParseWebPrintWriteResultCallback(napi_env env, napi_value argv)
4785 {
4786 if (!argv) {
4787 WVLOG_E("ParseWebPrintWriteResultCallback failed.");
4788 return nullptr;
4789 }
4790 napi_ref jsCallback = nullptr;
4791 napi_create_reference(env, argv, 1, &jsCallback);
4792 if (jsCallback) {
4793 WebPrintWriteResultCallback callbackImpl =
4794 [env, jCallback = std::move(jsCallback)](std::string jobId, uint32_t state) {
4795 if (!env) {
4796 return;
4797 }
4798 napi_handle_scope scope = nullptr;
4799 napi_open_handle_scope(env, &scope);
4800 if (scope == nullptr) {
4801 return;
4802 }
4803 napi_value setResult[INTEGER_TWO] = {0};
4804 napi_create_string_utf8(env, jobId.c_str(), NAPI_AUTO_LENGTH, &setResult[INTEGER_ZERO]);
4805 napi_create_uint32(env, state, &setResult[INTEGER_ONE]);
4806 napi_value args[INTEGER_TWO] = {setResult[INTEGER_ZERO], setResult[INTEGER_ONE]};
4807 napi_value callback = nullptr;
4808 napi_get_reference_value(env, jCallback, &callback);
4809 napi_value callbackResult = nullptr;
4810 napi_call_function(env, nullptr, callback, INTEGER_TWO, args, &callbackResult);
4811 napi_delete_reference(env, jCallback);
4812 napi_close_handle_scope(env, scope);
4813 };
4814 return callbackImpl;
4815 }
4816 return nullptr;
4817 }
4818
ParseWebPrintAttrParams(napi_env env,napi_value obj,PrintAttributesAdapter & printAttr)4819 bool ParseWebPrintAttrParams(napi_env env, napi_value obj, PrintAttributesAdapter& printAttr)
4820 {
4821 if (!obj) {
4822 WVLOG_E("ParseWebPrintAttrParams failed.");
4823 return false;
4824 }
4825 napi_value copyNumber = nullptr;
4826 napi_value pageRange = nullptr;
4827 napi_value isSequential = nullptr;
4828 napi_value pageSize = nullptr;
4829 napi_value isLandscape = nullptr;
4830 napi_value colorMode = nullptr;
4831 napi_value duplexMode = nullptr;
4832 napi_value margin = nullptr;
4833 napi_value option = nullptr;
4834 napi_get_named_property(env, obj, "copyNumber", ©Number);
4835 napi_get_named_property(env, obj, "pageRange", &pageRange);
4836 napi_get_named_property(env, obj, "isSequential", &isSequential);
4837 napi_get_named_property(env, obj, "pageSize", &pageSize);
4838 napi_get_named_property(env, obj, "isLandscape", &isLandscape);
4839 napi_get_named_property(env, obj, "colorMode", &colorMode);
4840 napi_get_named_property(env, obj, "duplexMode", &duplexMode);
4841 napi_get_named_property(env, obj, "margin", &margin);
4842 napi_get_named_property(env, obj, "option", &option);
4843 if (copyNumber) {
4844 NapiParseUtils::ParseUint32(env, copyNumber, printAttr.copyNumber);
4845 }
4846 if (isSequential) {
4847 NapiParseUtils::ParseBoolean(env, isSequential, printAttr.isSequential);
4848 }
4849 if (isLandscape) {
4850 NapiParseUtils::ParseBoolean(env, isLandscape, printAttr.isLandscape);
4851 }
4852 if (colorMode) {
4853 NapiParseUtils::ParseUint32(env, colorMode, printAttr.colorMode);
4854 }
4855 if (duplexMode) {
4856 NapiParseUtils::ParseUint32(env, duplexMode, printAttr.duplexMode);
4857 }
4858 if (option) {
4859 NapiParseUtils::ParseString(env, option, printAttr.option);
4860 }
4861 ParsePrintRangeAdapter(env, pageRange, printAttr);
4862 ParsePrintPageSizeAdapter(env, pageSize, printAttr);
4863 ParsePrintMarginAdapter(env, margin, printAttr);
4864 return true;
4865 }
4866
OnStartLayoutWrite(napi_env env,napi_callback_info info)4867 napi_value NapiWebPrintDocument::OnStartLayoutWrite(napi_env env, napi_callback_info info)
4868 {
4869 WVLOG_I("On Start Layout Write.");
4870 napi_value thisVar = nullptr;
4871 napi_value result = nullptr;
4872 size_t argc = INTEGER_FIVE;
4873 napi_value argv[INTEGER_FIVE] = { 0 };
4874 WebPrintDocument *webPrintDocument = nullptr;
4875
4876 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
4877 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webPrintDocument));
4878 if (webPrintDocument == nullptr) {
4879 WVLOG_E("unwrap webPrintDocument failed.");
4880 return result;
4881 }
4882
4883 std::string jobId;
4884 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], jobId)) {
4885 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4886 return result;
4887 }
4888
4889 int32_t fd;
4890 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_THREE], fd)) {
4891 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4892 return result;
4893 }
4894 PrintAttributesAdapter oldPrintAttr;
4895 PrintAttributesAdapter newPrintAttr;
4896 bool ret = false;
4897 ret = ParseWebPrintAttrParams(env, argv[INTEGER_ONE], oldPrintAttr);
4898 if (!ret) {
4899 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4900 return result;
4901 }
4902 ret = ParseWebPrintAttrParams(env, argv[INTEGER_TWO], newPrintAttr);
4903 if (!ret) {
4904 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4905 return result;
4906 }
4907 WebPrintWriteResultCallback writeResultCallback = nullptr;
4908 writeResultCallback = ParseWebPrintWriteResultCallback(env, argv[INTEGER_FOUR]);
4909 webPrintDocument->OnStartLayoutWrite(jobId, oldPrintAttr, newPrintAttr, fd, writeResultCallback);
4910 return result;
4911 }
4912
OnJobStateChanged(napi_env env,napi_callback_info info)4913 napi_value NapiWebPrintDocument::OnJobStateChanged(napi_env env, napi_callback_info info)
4914 {
4915 WVLOG_I("On Job State Changed.");
4916 napi_value thisVar = nullptr;
4917 napi_value result = nullptr;
4918 size_t argc = INTEGER_TWO;
4919 napi_value argv[INTEGER_TWO];
4920 NAPI_CALL(env, napi_get_undefined(env, &result));
4921
4922 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4923 WebPrintDocument *webPrintDocument = nullptr;
4924 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webPrintDocument));
4925 if (webPrintDocument == nullptr) {
4926 WVLOG_E("unwrap webPrintDocument failed.");
4927 return result;
4928 }
4929 if (argc != INTEGER_TWO) {
4930 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4931 return result;
4932 }
4933
4934 std::string jobId;
4935 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], jobId)) {
4936 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4937 return result;
4938 }
4939
4940 int32_t state;
4941 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ONE], state)) {
4942 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4943 return result;
4944 }
4945 webPrintDocument->OnJobStateChanged(jobId, state);
4946 return result;
4947 }
4948
JsConstructor(napi_env env,napi_callback_info info)4949 napi_value NapiWebPrintDocument::JsConstructor(napi_env env, napi_callback_info info)
4950 {
4951 napi_value thisVar = nullptr;
4952 size_t argc = INTEGER_ONE;
4953 napi_value argv[INTEGER_ONE];
4954 uint64_t addrWebPrintDoc = 0;
4955 bool loseLess = true;
4956 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
4957
4958 if (!NapiParseUtils::ParseUint64(env, argv[INTEGER_ZERO], addrWebPrintDoc, &loseLess)) {
4959 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
4960 return nullptr;
4961 }
4962 void *webPrintDocPtr = reinterpret_cast<void *>(addrWebPrintDoc);
4963 WebPrintDocument *webPrintDoc = new (std::nothrow) WebPrintDocument(webPrintDocPtr);
4964 if (webPrintDoc == nullptr) {
4965 WVLOG_E("new web print failed");
4966 return nullptr;
4967 }
4968 NAPI_CALL(env, napi_wrap(env, thisVar, webPrintDoc,
4969 [](napi_env env, void *data, void *hint) {
4970 WebPrintDocument *webPrintDocument = static_cast<WebPrintDocument *>(data);
4971 delete webPrintDocument;
4972 },
4973 nullptr, nullptr));
4974 return thisVar;
4975 }
4976
SetDownloadDelegate(napi_env env,napi_callback_info info)4977 napi_value NapiWebviewController::SetDownloadDelegate(napi_env env, napi_callback_info info)
4978 {
4979 WVLOG_D("WebDownloader::JS_SetDownloadDelegate");
4980 NWebHelper::Instance().LoadNWebSDK();
4981
4982 size_t argc = 1;
4983 napi_value argv[1] = {0};
4984 napi_value thisVar = nullptr;
4985 void* data = nullptr;
4986 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
4987
4988 WebDownloadDelegate* delegate = nullptr;
4989 napi_value obj = argv[0];
4990 napi_unwrap(env, obj, (void**)&delegate);
4991 if (!delegate) {
4992 WVLOG_E("[DOWNLOAD] WebDownloader::JS_SetDownloadDelegate delegate is null");
4993 (void)RemoveDownloadDelegateRef(env, thisVar);
4994 return nullptr;
4995 }
4996 napi_create_reference(env, obj, 1, &delegate->delegate_);
4997
4998 WebviewController *webviewController = nullptr;
4999 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
5000 if (webviewController == nullptr || !webviewController->IsInit()) {
5001 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
5002 WVLOG_E("create message port failed, napi unwrap webviewController failed");
5003 return nullptr;
5004 }
5005 int32_t nwebId = webviewController->GetWebId();
5006 WebDownloadManager::AddDownloadDelegateForWeb(nwebId, delegate);
5007 return nullptr;
5008 }
5009
StartDownload(napi_env env,napi_callback_info info)5010 napi_value NapiWebviewController::StartDownload(napi_env env, napi_callback_info info)
5011 {
5012 WVLOG_D("[DOWNLOAD] NapiWebviewController::StartDownload");
5013 size_t argc = 1;
5014 napi_value argv[1] = {0};
5015 napi_value thisVar = nullptr;
5016 void* data = nullptr;
5017 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
5018
5019 WebviewController *webviewController = nullptr;
5020 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
5021 if (webviewController == nullptr || !webviewController->IsInit()) {
5022 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
5023 WVLOG_E("create message port failed, napi unwrap webviewController failed");
5024 return nullptr;
5025 }
5026
5027 std::string url;
5028 if (!ParsePrepareUrl(env, argv[INTEGER_ZERO], url)) {
5029 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
5030 return nullptr;
5031 }
5032 int32_t nwebId = webviewController->GetWebId();
5033 NWebHelper::Instance().LoadNWebSDK();
5034 WebDownloader_StartDownload(nwebId, url.c_str());
5035 return nullptr;
5036 }
5037
SetConnectionTimeout(napi_env env,napi_callback_info info)5038 napi_value NapiWebviewController::SetConnectionTimeout(napi_env env, napi_callback_info info)
5039 {
5040 napi_value result = nullptr;
5041 size_t argc = INTEGER_ONE;
5042 napi_value argv[INTEGER_ONE] = { nullptr };
5043 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
5044 if (argc != INTEGER_ONE) {
5045 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5046 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
5047 return result;
5048 }
5049
5050 int32_t timeout = 0;
5051 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], timeout) || (timeout <= 0)) {
5052 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5053 "BusinessError: 401. Parameter error. The type of 'timeout' must be int and must be positive integer.");
5054 return result;
5055 }
5056
5057 NWebHelper::Instance().SetConnectionTimeout(timeout);
5058 NAPI_CALL(env, napi_get_undefined(env, &result));
5059 return result;
5060 }
5061
SetPrintBackground(napi_env env,napi_callback_info info)5062 napi_value NapiWebviewController::SetPrintBackground(napi_env env, napi_callback_info info)
5063 {
5064 napi_value result = nullptr;
5065 napi_value thisVar = nullptr;
5066 size_t argc = INTEGER_ONE;
5067 napi_value argv[INTEGER_ONE] = { 0 };
5068
5069 NAPI_CALL(env, napi_get_undefined(env, &result));
5070 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5071 if (argc != INTEGER_ONE) {
5072 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5073 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
5074 return result;
5075 }
5076
5077 bool printBackgroundEnabled = false;
5078 if (!NapiParseUtils::ParseBoolean(env, argv[0], printBackgroundEnabled)) {
5079 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5080 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "enable", "boolean"));
5081 return result;
5082 }
5083
5084 WebviewController *webviewController = GetWebviewController(env, info);
5085 if (!webviewController) {
5086 return result;
5087 }
5088 webviewController->SetPrintBackground(printBackgroundEnabled);
5089 return result;
5090 }
5091
GetPrintBackground(napi_env env,napi_callback_info info)5092 napi_value NapiWebviewController::GetPrintBackground(napi_env env, napi_callback_info info)
5093 {
5094 napi_value result = nullptr;
5095 WebviewController *webviewController = GetWebviewController(env, info);
5096
5097 if (!webviewController) {
5098 return result;
5099 }
5100
5101 bool printBackgroundEnabled = webviewController->GetPrintBackground();
5102 NAPI_CALL(env, napi_get_boolean(env, printBackgroundEnabled, &result));
5103 return result;
5104 }
5105
SetWebSchemeHandler(napi_env env,napi_callback_info info)5106 napi_value NapiWebviewController::SetWebSchemeHandler(napi_env env, napi_callback_info info)
5107 {
5108 size_t argc = 2;
5109 napi_value argv[2] = {0};
5110 napi_value thisVar = nullptr;
5111 void* data = nullptr;
5112 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
5113
5114 WebviewController *webviewController = nullptr;
5115 NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&webviewController));
5116 if (webviewController == nullptr || !webviewController->IsInit()) {
5117 BusinessError::ThrowErrorByErrcode(env, INIT_ERROR);
5118 WVLOG_E("create message port failed, napi unwrap webviewController failed");
5119 return nullptr;
5120 }
5121
5122 std::string scheme = "";
5123 if (!NapiParseUtils::ParseString(env, argv[0], scheme)) {
5124 WVLOG_E("NapiWebviewController::SetWebSchemeHandler parse scheme failed");
5125 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5126 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "scheme", "string"));
5127 return nullptr;
5128 }
5129
5130 WebSchemeHandler* handler = nullptr;
5131 napi_value obj = argv[1];
5132 napi_unwrap(env, obj, (void**)&handler);
5133 if (!handler) {
5134 WVLOG_E("NapiWebviewController::SetWebSchemeHandler handler is null");
5135 return nullptr;
5136 }
5137 napi_create_reference(env, obj, 1, &handler->delegate_);
5138
5139 if (!webviewController->SetWebSchemeHandler(scheme.c_str(), handler)) {
5140 WVLOG_E("NapiWebviewController::SetWebSchemeHandler failed");
5141 }
5142 return nullptr;
5143 }
5144
ClearWebSchemeHandler(napi_env env,napi_callback_info info)5145 napi_value NapiWebviewController::ClearWebSchemeHandler(napi_env env, napi_callback_info info)
5146 {
5147 napi_value result = nullptr;
5148 WebviewController *webviewController = GetWebviewController(env, info);
5149 if (!webviewController) {
5150 return nullptr;
5151 }
5152
5153 int32_t ret = webviewController->ClearWebSchemeHandler();
5154 if (ret != 0) {
5155 WVLOG_E("NapiWebviewController::ClearWebSchemeHandler failed");
5156 }
5157 NAPI_CALL(env, napi_get_undefined(env, &result));
5158 return result;
5159 }
5160
SetServiceWorkerWebSchemeHandler(napi_env env,napi_callback_info info)5161 napi_value NapiWebviewController::SetServiceWorkerWebSchemeHandler(
5162 napi_env env, napi_callback_info info)
5163 {
5164 size_t argc = 2;
5165 napi_value argv[2] = {0};
5166 napi_value thisVar = nullptr;
5167 void* data = nullptr;
5168 napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
5169
5170 std::string scheme = "";
5171 if (!NapiParseUtils::ParseString(env, argv[0], scheme)) {
5172 WVLOG_E("NapiWebviewController::SetWebSchemeHandler parse scheme failed");
5173 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5174 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "scheme", "string"));
5175 return nullptr;
5176 }
5177
5178 WebSchemeHandler* handler = nullptr;
5179 napi_value obj = argv[1];
5180 napi_unwrap(env, obj, (void**)&handler);
5181 if (!handler) {
5182 WVLOG_E("NapiWebviewController::SetServiceWorkerWebSchemeHandler handler is null");
5183 return nullptr;
5184 }
5185 napi_create_reference(env, obj, 1, &handler->delegate_);
5186
5187 if (!WebviewController::SetWebServiveWorkerSchemeHandler(
5188 scheme.c_str(), handler)) {
5189 WVLOG_E("NapiWebviewController::SetWebSchemeHandler failed");
5190 }
5191 return nullptr;
5192 }
5193
ClearServiceWorkerWebSchemeHandler(napi_env env,napi_callback_info info)5194 napi_value NapiWebviewController::ClearServiceWorkerWebSchemeHandler(
5195 napi_env env, napi_callback_info info)
5196 {
5197 int32_t ret = WebviewController::ClearWebServiceWorkerSchemeHandler();
5198 if (ret != 0) {
5199 WVLOG_E("ClearServiceWorkerWebSchemeHandler ret=%{public}d", ret);
5200 return nullptr;
5201 }
5202 return nullptr;
5203 }
5204
EnableIntelligentTrackingPrevention(napi_env env,napi_callback_info info)5205 napi_value NapiWebviewController::EnableIntelligentTrackingPrevention(
5206 napi_env env, napi_callback_info info)
5207 {
5208 WVLOG_I("enable/disable intelligent tracking prevention.");
5209 napi_value result = nullptr;
5210 napi_value thisVar = nullptr;
5211 size_t argc = INTEGER_ONE;
5212 napi_value argv[INTEGER_ONE] = { 0 };
5213
5214 NAPI_CALL(env, napi_get_undefined(env, &result));
5215 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5216 if (argc != INTEGER_ONE) {
5217 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5218 "BusinessError 401: Parameter error. The number of params must be one.");
5219 return result;
5220 }
5221
5222 bool enabled = false;
5223 if (!NapiParseUtils::ParseBoolean(env, argv[INTEGER_ZERO], enabled)) {
5224 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5225 "BusinessError 401: Parameter error. The type of 'enable' must be boolean.");
5226 return result;
5227 }
5228
5229 WebviewController *webviewController = GetWebviewController(env, info);
5230 if (!webviewController) {
5231 WVLOG_E("EnableIntelligentTrackingPrevention failed for webviewController failed");
5232 return result;
5233 }
5234 webviewController->EnableIntelligentTrackingPrevention(enabled);
5235 return result;
5236 }
5237
IsIntelligentTrackingPreventionEnabled(napi_env env,napi_callback_info info)5238 napi_value NapiWebviewController::IsIntelligentTrackingPreventionEnabled(
5239 napi_env env, napi_callback_info info)
5240 {
5241 WVLOG_I("get intelligent tracking prevention enabled value.");
5242 napi_value result = nullptr;
5243 WebviewController *webviewController = GetWebviewController(env, info);
5244
5245 if (!webviewController) {
5246 WVLOG_E("IsIntelligentTrackingPreventionEnabled failed for webviewController failed");
5247 return result;
5248 }
5249
5250 bool enabled = webviewController->
5251 IsIntelligentTrackingPreventionEnabled();
5252 NAPI_CALL(env, napi_get_boolean(env, enabled, &result));
5253 return result;
5254 }
5255
GetHostList(napi_env env,napi_value array,std::vector<std::string> & hosts)5256 bool GetHostList(napi_env env, napi_value array, std::vector<std::string>& hosts)
5257 {
5258 uint32_t arrayLen = 0;
5259 napi_get_array_length(env, array, &arrayLen);
5260 if (arrayLen == 0) {
5261 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5262 "BusinessError 401: Parameter error. The array length must be greater than 0.");
5263 return false;
5264 }
5265
5266 for (uint32_t i = 0; i < arrayLen; i++) {
5267 napi_value hostItem = nullptr;
5268 napi_get_element(env, array, i, &hostItem);
5269
5270 size_t hostLen = 0;
5271 napi_get_value_string_utf8(env, hostItem, nullptr, 0, &hostLen);
5272 if (hostLen == 0 || hostLen > UINT_MAX) {
5273 WVLOG_E("hostitem length is invalid");
5274 return false;
5275 }
5276
5277 char host[hostLen + 1];
5278 int retCode = memset_s(host, sizeof(host), 0, hostLen + 1);
5279 if (retCode < 0) {
5280 WVLOG_E("memset_s failed, retCode=%{public}d", retCode);
5281 return false;
5282 }
5283 napi_get_value_string_utf8(env, hostItem, host, sizeof(host), &hostLen);
5284 std::string hostStr(host);
5285 hosts.emplace_back(hostStr);
5286 }
5287 return true;
5288 }
5289
AddIntelligentTrackingPreventionBypassingList(napi_env env,napi_callback_info info)5290 napi_value NapiWebviewController::AddIntelligentTrackingPreventionBypassingList(
5291 napi_env env, napi_callback_info info)
5292 {
5293 WVLOG_I("Add intelligent tracking prevention bypassing list.");
5294 napi_value result = nullptr;
5295 napi_value thisVar = nullptr;
5296 size_t argc = INTEGER_ONE;
5297 napi_value argv[INTEGER_ONE] = { 0 };
5298 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5299 if (argc != INTEGER_ONE) {
5300 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5301 "BusinessError 401: Parameter error. The number of params must be one.");
5302 return result;
5303 }
5304
5305 bool isArray = false;
5306 NAPI_CALL(env, napi_is_array(env, argv[INTEGER_ZERO], &isArray));
5307 if (!isArray) {
5308 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5309 "BusinessError 401: Parameter error. The type of 'hostList' must be string array.");
5310 return result;
5311 }
5312
5313 std::vector<std::string> hosts;
5314 if (!GetHostList(env, argv[INTEGER_ZERO], hosts)) {
5315 WVLOG_E("get host list failed, GetHostList fail");
5316 return result;
5317 }
5318
5319 NWebHelper::Instance().AddIntelligentTrackingPreventionBypassingList(hosts);
5320 NAPI_CALL(env, napi_get_undefined(env, &result));
5321 return result;
5322 }
5323
RemoveIntelligentTrackingPreventionBypassingList(napi_env env,napi_callback_info info)5324 napi_value NapiWebviewController::RemoveIntelligentTrackingPreventionBypassingList(
5325 napi_env env, napi_callback_info info)
5326 {
5327 WVLOG_I("Remove intelligent tracking prevention bypassing list.");
5328 napi_value result = nullptr;
5329 napi_value thisVar = nullptr;
5330 size_t argc = INTEGER_ONE;
5331 napi_value argv[INTEGER_ONE] = { 0 };
5332 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5333 if (argc != INTEGER_ONE) {
5334 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5335 "BusinessError 401: Parameter error. The number of params must be one.");
5336 return result;
5337 }
5338
5339 bool isArray = false;
5340 NAPI_CALL(env, napi_is_array(env, argv[INTEGER_ZERO], &isArray));
5341 if (!isArray) {
5342 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5343 "BusinessError 401: Parameter error. The type of 'hostList' must be string array.");
5344 return result;
5345 }
5346
5347 std::vector<std::string> hosts;
5348 if (!GetHostList(env, argv[INTEGER_ZERO], hosts)) {
5349 WVLOG_E("get host list failed, GetHostList fail");
5350 return result;
5351 }
5352
5353 NWebHelper::Instance().RemoveIntelligentTrackingPreventionBypassingList(hosts);
5354 NAPI_CALL(env, napi_get_undefined(env, &result));
5355 return result;
5356 }
5357
ClearIntelligentTrackingPreventionBypassingList(napi_env env,napi_callback_info info)5358 napi_value NapiWebviewController::ClearIntelligentTrackingPreventionBypassingList(
5359 napi_env env, napi_callback_info info)
5360 {
5361 napi_value result = nullptr;
5362 WVLOG_I("Clear intelligent tracking prevention bypassing list.");
5363 NWebHelper::Instance().ClearIntelligentTrackingPreventionBypassingList();
5364 NAPI_CALL(env, napi_get_undefined(env, &result));
5365 return result;
5366 }
5367
PauseAllTimers(napi_env env,napi_callback_info info)5368 napi_value NapiWebviewController::PauseAllTimers(napi_env env, napi_callback_info info)
5369 {
5370 napi_value result = nullptr;
5371 NWebHelper::Instance().PauseAllTimers();
5372 NAPI_CALL(env, napi_get_undefined(env, &result));
5373 return result;
5374 }
5375
ResumeAllTimers(napi_env env,napi_callback_info info)5376 napi_value NapiWebviewController::ResumeAllTimers(napi_env env, napi_callback_info info)
5377 {
5378 napi_value result = nullptr;
5379 NWebHelper::Instance().ResumeAllTimers();
5380 NAPI_CALL(env, napi_get_undefined(env, &result));
5381 return result;
5382 }
5383
StartCamera(napi_env env,napi_callback_info info)5384 napi_value NapiWebviewController::StartCamera(napi_env env, napi_callback_info info)
5385 {
5386 napi_value result = nullptr;
5387 NAPI_CALL(env, napi_get_undefined(env, &result));
5388 WebviewController* webviewController = GetWebviewController(env, info);
5389 if (!webviewController) {
5390 return result;
5391 }
5392 webviewController->StartCamera();
5393
5394 return result;
5395 }
5396
StopCamera(napi_env env,napi_callback_info info)5397 napi_value NapiWebviewController::StopCamera(napi_env env, napi_callback_info info)
5398 {
5399 napi_value result = nullptr;
5400 NAPI_CALL(env, napi_get_undefined(env, &result));
5401 WebviewController* webviewController = GetWebviewController(env, info);
5402 if (!webviewController) {
5403 return result;
5404 }
5405 webviewController->StopCamera();
5406
5407 return result;
5408 }
5409
CloseCamera(napi_env env,napi_callback_info info)5410 napi_value NapiWebviewController::CloseCamera(napi_env env, napi_callback_info info)
5411 {
5412 napi_value result = nullptr;
5413 NAPI_CALL(env, napi_get_undefined(env, &result));
5414 WebviewController* webviewController = GetWebviewController(env, info);
5415 if (!webviewController) {
5416 return result;
5417 }
5418 webviewController->CloseCamera();
5419
5420 return result;
5421 }
5422
OnCreateNativeMediaPlayer(napi_env env,napi_callback_info info)5423 napi_value NapiWebviewController::OnCreateNativeMediaPlayer(napi_env env, napi_callback_info info)
5424 {
5425 WVLOG_D("put on_create_native_media_player callback");
5426
5427 size_t argc = INTEGER_ONE;
5428 napi_value value = nullptr;
5429 napi_value argv[INTEGER_ONE];
5430 napi_get_cb_info(env, info, &argc, argv, &value, nullptr);
5431 if (argc != INTEGER_ONE) {
5432 WVLOG_E("arg count %{public}zu is not equal to 1", argc);
5433 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5434 return nullptr;
5435 }
5436
5437 napi_valuetype valueType = napi_undefined;
5438 napi_typeof(env, argv[INTEGER_ZERO], &valueType);
5439 if (valueType != napi_function) {
5440 WVLOG_E("arg type is invalid");
5441 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5442 return nullptr;
5443 }
5444
5445 napi_ref callback = nullptr;
5446 napi_create_reference(env, argv[INTEGER_ZERO], INTEGER_ONE, &callback);
5447 if (!callback) {
5448 WVLOG_E("failed to create reference for callback");
5449 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5450 return nullptr;
5451 }
5452
5453 WebviewController* webviewController = GetWebviewController(env, info);
5454 if (!webviewController || !webviewController->IsInit()) {
5455 WVLOG_E("webview controller is null or not init");
5456 napi_delete_reference(env, callback);
5457 return nullptr;
5458 }
5459
5460 webviewController->OnCreateNativeMediaPlayer(env, std::move(callback));
5461 return nullptr;
5462 }
5463
SetRenderProcessMode(napi_env env,napi_callback_info info)5464 napi_value NapiWebviewController::SetRenderProcessMode(
5465 napi_env env, napi_callback_info info)
5466 {
5467 WVLOG_I("set render process mode.");
5468 napi_value result = nullptr;
5469 napi_value thisVar = nullptr;
5470 size_t argc = INTEGER_ONE;
5471 napi_value argv[INTEGER_ONE] = { 0 };
5472
5473 NAPI_CALL(env, napi_get_undefined(env, &result));
5474 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5475 if (argc != INTEGER_ONE) {
5476 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5477 "BusinessError 401: Parameter error. The number of params must be one.");
5478 return result;
5479 }
5480
5481 int32_t mode = 0;
5482 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], mode)) {
5483 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5484 "BusinessError 401: Parameter error. The type of 'mode' must be int.");
5485 return result;
5486 }
5487
5488 NWebHelper::Instance().SetRenderProcessMode(
5489 static_cast<RenderProcessMode>(mode));
5490
5491 return result;
5492 }
5493
GetRenderProcessMode(napi_env env,napi_callback_info info)5494 napi_value NapiWebviewController::GetRenderProcessMode(
5495 napi_env env, napi_callback_info info)
5496 {
5497 WVLOG_I("get render mode.");
5498 napi_value result = nullptr;
5499
5500 int32_t mode = static_cast<int32_t>(NWebHelper::Instance().GetRenderProcessMode());
5501 NAPI_CALL(env, napi_create_int32(env, mode, &result));
5502 return result;
5503 }
5504
PrecompileJavaScript(napi_env env,napi_callback_info info)5505 napi_value NapiWebviewController::PrecompileJavaScript(napi_env env, napi_callback_info info)
5506 {
5507 napi_value thisVar = nullptr;
5508 napi_value result = nullptr;
5509 size_t argc = INTEGER_THREE;
5510 napi_value argv[INTEGER_THREE] = {0};
5511 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5512 if (argc != INTEGER_THREE) {
5513 WVLOG_E("BusinessError: 401. Args count of 'PrecompileJavaScript' must be 3.");
5514 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5515 return result;
5516 }
5517
5518 WebviewController* webviewController = GetWebviewController(env, info);
5519 if (!webviewController) {
5520 WVLOG_E("PrecompileJavaScript: init webview controller error.");
5521 return result;
5522 }
5523
5524 std::string url;
5525 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], url) || url.empty()) {
5526 WVLOG_E("BusinessError: 401. The type of 'url' must be string.");
5527 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5528 return result;
5529 }
5530
5531 std::string script;
5532 bool parseResult = webviewController->ParseScriptContent(env, argv[INTEGER_ONE], script);
5533 if (!parseResult) {
5534 WVLOG_E("BusinessError: 401. The type of 'script' must be string or Uint8Array.");
5535 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5536 return result;
5537 }
5538
5539 auto cacheOptions = webviewController->ParseCacheOptions(env, argv[INTEGER_TWO]);
5540
5541 napi_deferred deferred = nullptr;
5542 napi_value promise = nullptr;
5543 napi_create_promise(env, &deferred, &promise);
5544 if (promise && deferred) {
5545 webviewController->PrecompileJavaScriptPromise(env, deferred, url, script, cacheOptions);
5546 return promise;
5547 }
5548
5549 return promise;
5550 }
5551
EnableBackForwardCache(napi_env env,napi_callback_info info)5552 napi_value NapiWebviewController::EnableBackForwardCache(napi_env env, napi_callback_info info)
5553 {
5554 napi_value thisVar = nullptr;
5555 napi_value result = nullptr;
5556 size_t argc = INTEGER_ONE;
5557 napi_value argv[INTEGER_ONE] = { 0 };
5558 napi_get_undefined(env, &result);
5559 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5560 if (argc != INTEGER_ONE) {
5561 WVLOG_E("EnalbeBackForwardCache: wrong number of params.");
5562 NWebHelper::Instance().EnableBackForwardCache(false, false);
5563 NAPI_CALL(env, napi_get_undefined(env, &result));
5564 return result;
5565 }
5566
5567 bool nativeEmbed = false;
5568 bool mediaTakeOver = false;
5569 napi_value embedObj = nullptr;
5570 napi_value mediaObj = nullptr;
5571 if (napi_get_named_property(env, argv[INTEGER_ZERO], "nativeEmbed", &embedObj) == napi_ok) {
5572 if (!NapiParseUtils::ParseBoolean(env, embedObj, nativeEmbed)) {
5573 nativeEmbed = false;
5574 }
5575 }
5576
5577 if (napi_get_named_property(env, argv[INTEGER_ZERO], "mediaTakeOver", &mediaObj) == napi_ok) {
5578 if (!NapiParseUtils::ParseBoolean(env, mediaObj, mediaTakeOver)) {
5579 mediaTakeOver = false;
5580 }
5581 }
5582
5583 NWebHelper::Instance().EnableBackForwardCache(nativeEmbed, mediaTakeOver);
5584 NAPI_CALL(env, napi_get_undefined(env, &result));
5585 return result;
5586 }
5587
SetBackForwardCacheOptions(napi_env env,napi_callback_info info)5588 napi_value NapiWebviewController::SetBackForwardCacheOptions(napi_env env, napi_callback_info info)
5589 {
5590 napi_value thisVar = nullptr;
5591 napi_value result = nullptr;
5592 size_t argc = INTEGER_ONE;
5593 napi_value argv[INTEGER_ONE] = { 0 };
5594 napi_get_undefined(env, &result);
5595 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5596 WebviewController* webviewController = GetWebviewController(env, info);
5597 if (!webviewController) {
5598 WVLOG_E("SetBackForwardCacheOptions: Init webview controller error.");
5599 return result;
5600 }
5601
5602 if (argc != INTEGER_ONE) {
5603 WVLOG_E("SetBackForwardCacheOptions: wrong number of params.");
5604 webviewController->SetBackForwardCacheOptions(
5605 BFCACHE_DEFAULT_SIZE, BFCACHE_DEFAULT_TIMETOLIVE);
5606 NAPI_CALL(env, napi_get_undefined(env, &result));
5607 return result;
5608 }
5609
5610 int32_t size = BFCACHE_DEFAULT_SIZE;
5611 int32_t timeToLive = BFCACHE_DEFAULT_TIMETOLIVE;
5612 napi_value sizeObj = nullptr;
5613 napi_value timeToLiveObj = nullptr;
5614 if (napi_get_named_property(env, argv[INTEGER_ZERO], "size", &sizeObj) == napi_ok) {
5615 if (!NapiParseUtils::ParseInt32(env, sizeObj, size)) {
5616 size = BFCACHE_DEFAULT_SIZE;
5617 }
5618 }
5619
5620 if (napi_get_named_property(env, argv[INTEGER_ZERO], "timeToLive", &timeToLiveObj) == napi_ok) {
5621 if (!NapiParseUtils::ParseInt32(env, timeToLiveObj, timeToLive)) {
5622 timeToLive = BFCACHE_DEFAULT_TIMETOLIVE;
5623 }
5624 }
5625
5626 webviewController->SetBackForwardCacheOptions(size, timeToLive);
5627 NAPI_CALL(env, napi_get_undefined(env, &result));
5628 return result;
5629 }
5630
InjectOfflineResources(napi_env env,napi_callback_info info)5631 napi_value NapiWebviewController::InjectOfflineResources(napi_env env, napi_callback_info info)
5632 {
5633 napi_value thisVar = nullptr;
5634 napi_value result = nullptr;
5635 size_t argc = INTEGER_ONE;
5636 napi_value argv[INTEGER_ONE] = {0};
5637 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5638 if (argc != INTEGER_ONE) {
5639 WVLOG_E("BusinessError: 401. Args count of 'InjectOfflineResource' must be 1.");
5640 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5641 return result;
5642 }
5643
5644 napi_value resourcesList = argv[INTEGER_ZERO];
5645 bool isArray = false;
5646 napi_is_array(env, resourcesList, &isArray);
5647 if (!isArray) {
5648 WVLOG_E("BusinessError: 401. The type of 'resourceMaps' must be Array");
5649 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5650 return result;
5651 }
5652
5653 AddResourcesToMemoryCache(env, info, resourcesList);
5654 return result;
5655 }
5656
AddResourcesToMemoryCache(napi_env env,napi_callback_info info,napi_value & resourcesList)5657 void NapiWebviewController::AddResourcesToMemoryCache(napi_env env,
5658 napi_callback_info info,
5659 napi_value& resourcesList)
5660 {
5661 uint32_t resourcesCount = 0;
5662 napi_get_array_length(env, resourcesList, &resourcesCount);
5663
5664 if (resourcesCount > MAX_RESOURCES_COUNT || resourcesCount == 0) {
5665 WVLOG_E("BusinessError: 401. The size of 'resourceMaps' must less than %{public}zu and not 0",
5666 MAX_RESOURCES_COUNT);
5667 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5668 return;
5669 }
5670
5671 for (uint32_t i = 0 ; i < resourcesCount ; i++) {
5672 napi_value urlListObj = nullptr;
5673 napi_value resourceObj = nullptr;
5674 napi_value headersObj = nullptr;
5675 napi_value typeObj = nullptr;
5676 napi_value obj = nullptr;
5677
5678 napi_create_array(env, &headersObj);
5679 napi_create_array(env, &urlListObj);
5680
5681 napi_get_element(env, resourcesList, i, &obj);
5682 if ((napi_get_named_property(env, obj, "urlList", &urlListObj) != napi_ok) ||
5683 (napi_get_named_property(env, obj, "resource", &resourceObj) != napi_ok) ||
5684 (napi_get_named_property(env, obj, "responseHeaders", &headersObj) != napi_ok) ||
5685 (napi_get_named_property(env, obj, "type", &typeObj) != napi_ok)) {
5686 WVLOG_E("InjectOfflineResources: parse params from resource map failed.");
5687 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5688 continue;
5689 }
5690
5691 OfflineResourceValue resourceValue;
5692 resourceValue.urlList = urlListObj;
5693 resourceValue.resource = resourceObj;
5694 resourceValue.responseHeaders = headersObj;
5695 resourceValue.type = typeObj;
5696 AddResourceItemToMemoryCache(env, info, resourceValue);
5697 }
5698 }
5699
AddResourceItemToMemoryCache(napi_env env,napi_callback_info info,OfflineResourceValue resourceValue)5700 void NapiWebviewController::AddResourceItemToMemoryCache(napi_env env,
5701 napi_callback_info info,
5702 OfflineResourceValue resourceValue)
5703 {
5704 WebviewController* webviewController = GetWebviewController(env, info);
5705 if (!webviewController) {
5706 WVLOG_E("InjectOfflineResource: init webview controller error.");
5707 return;
5708 }
5709
5710 std::vector<std::string> urlList;
5711 ParseURLResult result = webviewController->ParseURLList(env, resourceValue.urlList, urlList);
5712 if (result != ParseURLResult::OK) {
5713 auto errCode = result == ParseURLResult::FAILED ? PARAM_CHECK_ERROR : INVALID_URL;
5714 if (errCode == PARAM_CHECK_ERROR) {
5715 WVLOG_E("BusinessError: 401. The type of 'urlList' must be Array of string.");
5716 }
5717 BusinessError::ThrowErrorByErrcode(env, errCode);
5718 return;
5719 }
5720
5721 std::vector<uint8_t> resource = webviewController->ParseUint8Array(env, resourceValue.resource);
5722 if (resource.empty() || resource.size() > MAX_RESOURCE_SIZE) {
5723 WVLOG_E("BusinessError: 401. The type of 'resource' must be Uint8Array. "
5724 "'resource' size must less than %{public}zu and must not be empty.", MAX_RESOURCE_SIZE);
5725 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5726 return;
5727 }
5728
5729 std::map<std::string, std::string> responseHeaders;
5730 if (!webviewController->ParseResponseHeaders(env, resourceValue.responseHeaders, responseHeaders)) {
5731 WVLOG_E("BusinessError: 401. The type of 'responseHeaders' must be Array of 'WebHeader'.");
5732 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5733 return;
5734 }
5735
5736 uint32_t type = 0;
5737 if (!NapiParseUtils::ParseUint32(env, resourceValue.type, type)) {
5738 WVLOG_E("BusinessError: 401. The type of 'type' must be one kind of 'OfflineResourceType'.");
5739 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5740 return;
5741 }
5742
5743 webviewController->InjectOfflineResource(urlList, resource, responseHeaders, type);
5744 }
5745
SetHostIP(napi_env env,napi_callback_info info)5746 napi_value NapiWebviewController::SetHostIP(napi_env env, napi_callback_info info)
5747 {
5748 napi_value thisVar = nullptr;
5749 napi_value result = nullptr;
5750 size_t argc = INTEGER_THREE;
5751 napi_value argv[INTEGER_THREE] = { 0 };
5752 std::string hostName;
5753 std::string address;
5754 int32_t aliveTime = INTEGER_ZERO;
5755
5756 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5757 if (argc != INTEGER_THREE) {
5758 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5759 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "three"));
5760 return result;
5761 }
5762
5763 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], hostName) ||
5764 !NapiParseUtils::ParseString(env, argv[INTEGER_ONE], address) ||
5765 !NapiParseUtils::ParseInt32(env, argv[INTEGER_TWO], aliveTime)) {
5766 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR, ParamCheckErrorMsgTemplate::PARAM_TYEPS_ERROR);
5767 return result;
5768 }
5769
5770 if (!ParseIP(env, argv[INTEGER_ONE], address)) {
5771 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5772 "BusinessError 401: IP address error.");
5773 return result;
5774 }
5775
5776 NWebHelper::Instance().SetHostIP(hostName, address, aliveTime);
5777 NAPI_CALL(env, napi_get_undefined(env, &result));
5778
5779 return result;
5780 }
5781
ClearHostIP(napi_env env,napi_callback_info info)5782 napi_value NapiWebviewController::ClearHostIP(napi_env env, napi_callback_info info)
5783 {
5784 napi_value thisVar = nullptr;
5785 napi_value result = nullptr;
5786 size_t argc = INTEGER_ONE;
5787 napi_value argv[INTEGER_ONE] = { 0 };
5788 std::string hostName;
5789
5790 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5791 if (argc != INTEGER_ONE) {
5792 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5793 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
5794 return result;
5795 }
5796
5797 if (!NapiParseUtils::ParseString(env, argv[INTEGER_ZERO], hostName)) {
5798 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5799 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "hostName", "string"));
5800 return result;
5801 }
5802
5803 NWebHelper::Instance().ClearHostIP(hostName);
5804 NAPI_CALL(env, napi_get_undefined(env, &result));
5805 return result;
5806 }
5807
WarmupServiceWorker(napi_env env,napi_callback_info info)5808 napi_value NapiWebviewController::WarmupServiceWorker(napi_env env, napi_callback_info info)
5809 {
5810 napi_value thisVar = nullptr;
5811 napi_value result = nullptr;
5812 size_t argc = INTEGER_ONE;
5813 napi_value argv[INTEGER_ONE] = { 0 };
5814 napi_get_undefined(env, &result);
5815 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5816 if (argc != INTEGER_ONE) {
5817 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
5818 return result;
5819 }
5820
5821 std::string url;
5822 if (!ParsePrepareUrl(env, argv[INTEGER_ZERO], url)) {
5823 BusinessError::ThrowErrorByErrcode(env, INVALID_URL);
5824 return result;
5825 }
5826
5827 NWebHelper::Instance().WarmupServiceWorker(url);
5828 return result;
5829 }
5830
GetSurfaceId(napi_env env,napi_callback_info info)5831 napi_value NapiWebviewController::GetSurfaceId(napi_env env, napi_callback_info info)
5832 {
5833 napi_value result = nullptr;
5834 WebviewController *webviewController = GetWebviewController(env, info);
5835 if (!webviewController) {
5836 return nullptr;
5837 }
5838
5839 std::string surfaceId = webviewController->GetSurfaceId();
5840 napi_create_string_utf8(env, surfaceId.c_str(), surfaceId.length(), &result);
5841 return result;
5842 }
5843
EnableWholeWebPageDrawing(napi_env env,napi_callback_info info)5844 napi_value NapiWebviewController::EnableWholeWebPageDrawing(napi_env env, napi_callback_info info)
5845 {
5846 napi_value result = nullptr;
5847 NWebHelper::Instance().SetWholeWebDrawing();
5848 NAPI_CALL(env, napi_get_undefined(env, &result));
5849 return result;
5850 }
5851
EnableAdsBlock(napi_env env,napi_callback_info info)5852 napi_value NapiWebviewController::EnableAdsBlock(
5853 napi_env env, napi_callback_info info)
5854 {
5855 napi_value result = nullptr;
5856 napi_value thisVar = nullptr;
5857 size_t argc = INTEGER_ONE;
5858 napi_value argv[INTEGER_ONE] = { 0 };
5859
5860 NAPI_CALL(env, napi_get_undefined(env, &result));
5861 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5862 if (argc != INTEGER_ONE) {
5863 WVLOG_E("EnableAdsBlock: args count is not allowed.");
5864 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5865 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
5866 return result;
5867 }
5868
5869 bool enabled = false;
5870 if (!NapiParseUtils::ParseBoolean(env, argv[INTEGER_ZERO], enabled)) {
5871 WVLOG_E("EnableAdsBlock: the given enabled is not allowed.");
5872 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
5873 "BusinessError 401: Parameter error. The type of 'enable' must be boolean.");
5874 return result;
5875 }
5876
5877 WebviewController *webviewController = GetWebviewController(env, info);
5878 if (!webviewController) {
5879 WVLOG_E("EnableAdsBlock: init webview controller error.");
5880 return result;
5881 }
5882
5883 WVLOG_I("EnableAdsBlock: %{public}s", (enabled ? "true" : "false"));
5884 webviewController->EnableAdsBlock(enabled);
5885 return result;
5886 }
5887
IsAdsBlockEnabled(napi_env env,napi_callback_info info)5888 napi_value NapiWebviewController::IsAdsBlockEnabled(napi_env env, napi_callback_info info)
5889 {
5890 napi_value result = nullptr;
5891 WebviewController *webviewController = GetWebviewController(env, info);
5892 if (!webviewController) {
5893 return nullptr;
5894 }
5895
5896 bool isAdsBlockEnabled = webviewController->IsAdsBlockEnabled();
5897 NAPI_CALL(env, napi_get_boolean(env, isAdsBlockEnabled, &result));
5898 return result;
5899 }
5900
IsAdsBlockEnabledForCurPage(napi_env env,napi_callback_info info)5901 napi_value NapiWebviewController::IsAdsBlockEnabledForCurPage(napi_env env, napi_callback_info info)
5902 {
5903 napi_value result = nullptr;
5904 WebviewController *webviewController = GetWebviewController(env, info);
5905 if (!webviewController) {
5906 return nullptr;
5907 }
5908
5909 bool isAdsBlockEnabledForCurPage = webviewController->IsAdsBlockEnabledForCurPage();
5910 NAPI_CALL(env, napi_get_boolean(env, isAdsBlockEnabledForCurPage, &result));
5911 return result;
5912 }
5913
CreateWebPageSnapshotResultCallback(napi_env env,napi_ref jsCallback,bool check,int32_t inputWidth,int32_t inputHeight)5914 WebSnapshotCallback CreateWebPageSnapshotResultCallback(
5915 napi_env env, napi_ref jsCallback, bool check, int32_t inputWidth, int32_t inputHeight)
5916 {
5917 return
5918 [env, jCallback = std::move(jsCallback), check, inputWidth, inputHeight](
5919 const char *returnId, bool returnStatus, float radio, void *returnData,
5920 int returnWidth, int returnHeight) {
5921 WVLOG_I("WebPageSnapshot return napi callback");
5922 napi_value jsResult = nullptr;
5923 napi_create_object(env, &jsResult);
5924
5925 napi_value jsPixelMap = nullptr;
5926 Media::InitializationOptions opt;
5927 opt.size.width = static_cast<int32_t>(returnWidth);
5928 opt.size.height = static_cast<int32_t>(returnHeight);
5929 opt.pixelFormat = Media::PixelFormat::RGBA_8888;
5930 opt.alphaType = Media::AlphaType::IMAGE_ALPHA_TYPE_OPAQUE;
5931 opt.editable = true;
5932 auto pixelMap = Media::PixelMap::Create(opt);
5933 if (pixelMap != nullptr) {
5934 uint64_t stride = static_cast<uint64_t>(returnWidth) << 2;
5935 uint64_t bufferSize = stride * static_cast<uint64_t>(returnHeight);
5936 pixelMap->WritePixels(static_cast<const uint8_t *>(returnData), bufferSize);
5937 std::shared_ptr<Media::PixelMap> pixelMapToJs(pixelMap.release());
5938 jsPixelMap = OHOS::Media::PixelMapNapi::CreatePixelMap(env, pixelMapToJs);
5939 } else {
5940 WVLOG_E("WebPageSnapshot create pixel map error");
5941 }
5942 napi_set_named_property(env, jsResult, "imagePixelMap", jsPixelMap);
5943
5944 int returnJsWidth = 0;
5945 int returnJsHeight = 0;
5946 if (radio > 0) {
5947 returnJsWidth = returnWidth / radio;
5948 returnJsHeight = returnHeight / radio;
5949 }
5950 if (check) {
5951 if (std::abs(returnJsWidth - inputWidth) < INTEGER_THREE) {
5952 returnJsWidth = inputWidth;
5953 }
5954
5955 if (std::abs(returnJsHeight - inputHeight) < INTEGER_THREE) {
5956 returnJsHeight = inputHeight;
5957 }
5958 }
5959 napi_value jsSizeObj = nullptr;
5960 napi_create_object(env, &jsSizeObj);
5961 napi_value jsSize[2] = {0};
5962 napi_create_int32(env, returnJsWidth, &jsSize[0]);
5963 napi_create_int32(env, returnJsHeight, &jsSize[1]);
5964 napi_set_named_property(env, jsSizeObj, "width", jsSize[0]);
5965 napi_set_named_property(env, jsSizeObj, "height", jsSize[1]);
5966 napi_set_named_property(env, jsResult, "size", jsSizeObj);
5967
5968 napi_value jsId = nullptr;
5969 napi_create_string_utf8(env, returnId, strlen(returnId), &jsId);
5970 napi_set_named_property(env, jsResult, "id", jsId);
5971
5972 napi_value jsStatus = nullptr;
5973 napi_get_boolean(env, returnStatus, &jsStatus);
5974 napi_set_named_property(env, jsResult, "status", jsStatus);
5975
5976 napi_value jsError = nullptr;
5977 napi_get_undefined(env, &jsError);
5978 napi_value args[INTEGER_TWO] = {jsError, jsResult};
5979
5980 napi_value callback = nullptr;
5981 napi_value callbackResult = nullptr;
5982 napi_get_reference_value(env, jCallback, &callback);
5983
5984 napi_call_function(env, nullptr, callback, INTEGER_TWO, args, &callbackResult);
5985 napi_delete_reference(env, jCallback);
5986 g_inWebPageSnapshot = false;
5987 };
5988 }
5989
WebPageSnapshot(napi_env env,napi_callback_info info)5990 napi_value NapiWebviewController::WebPageSnapshot(napi_env env, napi_callback_info info)
5991 {
5992 napi_value thisVar = nullptr;
5993 napi_value result = nullptr;
5994 size_t argc = INTEGER_TWO;
5995 napi_value argv[INTEGER_TWO] = {0};
5996
5997 napi_get_undefined(env, &result);
5998 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
5999
6000 if (argc != INTEGER_TWO) {
6001 WVLOG_E("WebPageSnapshot: args count is not allowed.");
6002 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
6003 return result;
6004 }
6005
6006 napi_ref callback = nullptr;
6007 napi_create_reference(env, argv[INTEGER_ONE], INTEGER_ONE, &callback);
6008 if (!callback) {
6009 WVLOG_E("WebPageSnapshot failed to create reference for callback");
6010 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
6011 return result;
6012 }
6013
6014 WebviewController *webviewController = GetWebviewController(env, info);
6015 if (!webviewController) {
6016 WVLOG_E("WebPageSnapshot init webview controller error.");
6017 napi_delete_reference(env, callback);
6018 return result;
6019 }
6020
6021 if (g_inWebPageSnapshot) {
6022 JsErrorCallback(env, std::move(callback), FUNCTION_NOT_ENABLE);
6023 napi_delete_reference(env, callback);
6024 return result;
6025 }
6026 g_inWebPageSnapshot = true;
6027
6028 napi_value snapshotId = nullptr;
6029 napi_value snapshotSize = nullptr;
6030 napi_value snapshotSizeWidth = nullptr;
6031 napi_value snapshotSizeHeight = nullptr;
6032
6033 std::string nativeSnapshotId = "";
6034 int32_t nativeSnapshotSizeWidth = 0;
6035 int32_t nativeSnapshotSizeHeight = 0;
6036 PixelUnit nativeSnapshotSizeWidthType = PixelUnit::NONE;
6037 PixelUnit nativeSnapshotSizeHeightType = PixelUnit::NONE;
6038 PixelUnit nativeSnapshotSizeType = PixelUnit::NONE;
6039
6040 if (napi_get_named_property(env, argv[INTEGER_ZERO], "id", &snapshotId) == napi_ok) {
6041 NapiParseUtils::ParseString(env, snapshotId, nativeSnapshotId);
6042 }
6043
6044 if (napi_get_named_property(env, argv[INTEGER_ZERO], "size", &snapshotSize) == napi_ok) {
6045 if (napi_get_named_property(env, snapshotSize, "width", &snapshotSizeWidth) == napi_ok) {
6046 if (!webviewController->ParseJsLengthToInt(env, snapshotSizeWidth,
6047 nativeSnapshotSizeWidthType,
6048 nativeSnapshotSizeWidth)) {
6049 JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR);
6050 g_inWebPageSnapshot = false;
6051 napi_delete_reference(env, callback);
6052 return result;
6053 }
6054 }
6055 if (napi_get_named_property(env, snapshotSize, "height", &snapshotSizeHeight) == napi_ok) {
6056 if (!webviewController->ParseJsLengthToInt(env, snapshotSizeHeight,
6057 nativeSnapshotSizeHeightType,
6058 nativeSnapshotSizeHeight)) {
6059 JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR);
6060 g_inWebPageSnapshot = false;
6061 napi_delete_reference(env, callback);
6062 return result;
6063 }
6064 }
6065 }
6066
6067 if (nativeSnapshotSizeWidthType != PixelUnit::NONE && nativeSnapshotSizeHeightType != PixelUnit::NONE &&
6068 nativeSnapshotSizeWidthType != nativeSnapshotSizeHeightType) {
6069 WVLOG_E("WebPageSnapshot input different pixel unit");
6070 JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR);
6071 g_inWebPageSnapshot = false;
6072 napi_delete_reference(env, callback);
6073 return result;
6074 }
6075
6076 if (nativeSnapshotSizeWidthType != PixelUnit::NONE) {
6077 nativeSnapshotSizeType = nativeSnapshotSizeWidthType;
6078 }
6079 if (nativeSnapshotSizeHeightType != PixelUnit::NONE) {
6080 nativeSnapshotSizeType = nativeSnapshotSizeHeightType;
6081 }
6082 if (nativeSnapshotSizeWidth < 0 || nativeSnapshotSizeHeight < 0) {
6083 WVLOG_E("WebPageSnapshot input pixel length less than 0");
6084 JsErrorCallback(env, std::move(callback), PARAM_CHECK_ERROR);
6085 g_inWebPageSnapshot = false;
6086 napi_delete_reference(env, callback);
6087 return result;
6088 }
6089 bool pixelCheck = false;
6090 if (nativeSnapshotSizeType == PixelUnit::VP) {
6091 pixelCheck = true;
6092 }
6093 WVLOG_I("WebPageSnapshot pixel type :%{public}d", static_cast<int>(nativeSnapshotSizeType));
6094
6095 auto resultCallback = CreateWebPageSnapshotResultCallback(
6096 env, std::move(callback), pixelCheck, nativeSnapshotSizeWidth, nativeSnapshotSizeHeight);
6097
6098 ErrCode ret = webviewController->WebPageSnapshot(nativeSnapshotId.c_str(),
6099 nativeSnapshotSizeType,
6100 nativeSnapshotSizeWidth,
6101 nativeSnapshotSizeHeight,
6102 std::move(resultCallback));
6103 if (ret != NO_ERROR) {
6104 g_inWebPageSnapshot = false;
6105 BusinessError::ThrowErrorByErrcode(env, ret);
6106 }
6107 return result;
6108 }
6109
SetUrlTrustList(napi_env env,napi_callback_info info)6110 napi_value NapiWebviewController::SetUrlTrustList(napi_env env, napi_callback_info info)
6111 {
6112 WVLOG_D("SetUrlTrustList invoked");
6113
6114 napi_value result = nullptr;
6115 NAPI_CALL(env, napi_get_undefined(env, &result));
6116
6117 napi_value thisVar = nullptr;
6118 size_t argc = INTEGER_ONE;
6119 napi_value argv[INTEGER_ONE] = { 0 };
6120 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
6121 if (argc != INTEGER_ONE) {
6122 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6123 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "one"));
6124 return result;
6125 }
6126
6127 std::string urlTrustList;
6128 if (!NapiParseUtils::ParseString(env, argv[0], urlTrustList)) {
6129 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6130 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "urlTrustList", "string"));
6131 return result;
6132 }
6133 if (urlTrustList.size() > MAX_URL_TRUST_LIST_STR_LEN) {
6134 WVLOG_E("url trust list len is too large.");
6135 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
6136 return result;
6137 }
6138
6139 WebviewController* webviewController = GetWebviewController(env, info);
6140 if (!webviewController) {
6141 WVLOG_E("webview controller is null or not init");
6142 return result;
6143 }
6144
6145 std::string detailMsg;
6146 ErrCode ret = webviewController->SetUrlTrustList(urlTrustList, detailMsg);
6147 if (ret != NO_ERROR) {
6148 WVLOG_E("SetUrlTrustList failed, error code: %{public}d", ret);
6149 BusinessError::ThrowErrorByErrcode(env, ret,
6150 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_DETAIL_ERROR_MSG, detailMsg.c_str()));
6151 return result;
6152 }
6153 return result;
6154 }
6155
UpdateInstanceId(napi_env env,napi_callback_info info)6156 napi_value NapiWebviewController::UpdateInstanceId(napi_env env, napi_callback_info info)
6157 {
6158 WVLOG_D("Instance changed");
6159 napi_value result = nullptr;
6160 napi_value thisVar = nullptr;
6161 size_t argc = INTEGER_ONE;
6162 napi_value argv[INTEGER_ONE] = { 0 };
6163
6164 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
6165 if (argc != INTEGER_ONE) {
6166 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
6167 return result;
6168 }
6169
6170 int32_t newId = 0;
6171 if (!NapiParseUtils::ParseInt32(env, argv[INTEGER_ZERO], newId)) {
6172 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
6173 return result;
6174 }
6175
6176 WebviewController *webviewController = nullptr;
6177 napi_status status = napi_unwrap(env, thisVar, (void **)&webviewController);
6178 if ((!webviewController) || (status != napi_ok) || !webviewController->IsInit()) {
6179 return result;
6180 }
6181
6182 webviewController->UpdateInstanceId(newId);
6183
6184 NAPI_CALL(env, napi_get_undefined(env, &result));
6185 return result;
6186 }
6187
SetPathAllowingUniversalAccess(napi_env env,napi_callback_info info)6188 napi_value NapiWebviewController::SetPathAllowingUniversalAccess(
6189 napi_env env, napi_callback_info info)
6190 {
6191 napi_value result = nullptr;
6192 napi_value thisVar = nullptr;
6193 size_t argc = INTEGER_ONE;
6194 napi_value argv[INTEGER_ONE] = { 0 };
6195 NAPI_CALL(env, napi_get_undefined(env, &result));
6196 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
6197 WebviewController *webviewController = GetWebviewController(env, info);
6198 if (!webviewController) {
6199 WVLOG_E("SetPathAllowingUniversalAccess init webview controller error.");
6200 return result;
6201 }
6202 bool isArray = false;
6203 NAPI_CALL(env, napi_is_array(env, argv[INTEGER_ZERO], &isArray));
6204 if (!isArray) {
6205 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6206 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "pathList", "Array<string>"));
6207 return result;
6208 }
6209 std::vector<std::string> pathList;
6210 uint32_t pathCount = 0;
6211 NAPI_CALL(env, napi_get_array_length(env, argv[INTEGER_ZERO], &pathCount));
6212 for (uint32_t i = 0 ; i < pathCount ; i++) {
6213 napi_value pathItem = nullptr;
6214 napi_get_element(env, argv[INTEGER_ZERO], i, &pathItem);
6215 std::string path;
6216 if (!NapiParseUtils::ParseString(env, pathItem, path)) {
6217 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6218 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "pathList", "Array<string>"));
6219 return result;
6220 }
6221 if (path.empty()) {
6222 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6223 NWebError::FormatString("BusinessError 401: Parameter error. Path: '%s' is invalid", path.c_str()));
6224 return result;
6225 }
6226 pathList.emplace_back(path);
6227 }
6228 std::string errorPath;
6229 webviewController->SetPathAllowingUniversalAccess(pathList, errorPath);
6230 if (!errorPath.empty()) {
6231 WVLOG_E("%{public}s is invalid.", errorPath.c_str());
6232 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6233 NWebError::FormatString("BusinessError 401: Parameter error. Path: '%s' is invalid", errorPath.c_str()));
6234 }
6235 return result;
6236 }
6237
ScrollByWithResult(napi_env env,napi_callback_info info)6238 napi_value NapiWebviewController::ScrollByWithResult(napi_env env, napi_callback_info info)
6239 {
6240 napi_value thisVar = nullptr;
6241 napi_value result = nullptr;
6242 size_t argc = INTEGER_TWO;
6243 napi_value argv[INTEGER_TWO] = { 0 };
6244 float deltaX;
6245 float deltaY;
6246
6247 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
6248 if (argc != INTEGER_TWO) {
6249 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6250 NWebError::FormatString(ParamCheckErrorMsgTemplate::PARAM_NUMBERS_ERROR_ONE, "two"));
6251 return result;
6252 }
6253
6254 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ZERO], deltaX)) {
6255 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6256 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaX", "number"));
6257 return result;
6258 }
6259
6260 if (!NapiParseUtils::ParseFloat(env, argv[INTEGER_ONE], deltaY)) {
6261 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR,
6262 NWebError::FormatString(ParamCheckErrorMsgTemplate::TYPE_ERROR, "deltaY", "number"));
6263 return result;
6264 }
6265
6266 WebviewController *webviewController = GetWebviewController(env, info);
6267 if (!webviewController) {
6268 return nullptr;
6269 }
6270
6271 bool scrollByWithResult = webviewController->ScrollByWithResult(deltaX, deltaY);
6272 NAPI_CALL(env, napi_get_boolean(env, scrollByWithResult, &result));
6273 return result;
6274 }
6275
GetScrollOffset(napi_env env,napi_callback_info info)6276 napi_value NapiWebviewController::GetScrollOffset(napi_env env,
6277 napi_callback_info info)
6278 {
6279 napi_value result = nullptr;
6280 napi_value horizontal;
6281 napi_value vertical;
6282 float offsetX = 0;
6283 float offsetY = 0;
6284
6285 WebviewController* webviewController = GetWebviewController(env, info);
6286 if (!webviewController) {
6287 return nullptr;
6288 }
6289
6290 webviewController->GetScrollOffset(&offsetX, &offsetY);
6291
6292 napi_create_object(env, &result);
6293 napi_create_double(env, static_cast<double>(offsetX), &horizontal);
6294 napi_create_double(env, static_cast<double>(offsetY), &vertical);
6295 napi_set_named_property(env, result, "x", horizontal);
6296 napi_set_named_property(env, result, "y", vertical);
6297 return result;
6298 }
6299 } // namespace NWeb
6300 } // namespace OHOS
6301