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