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_function.h"
17
18 #include <unistd.h>
19 #include <uv.h>
20 #include "business_error.h"
21 #include "napi_parse_utils.h"
22 #include "nweb.h"
23 #include "nweb_helper.h"
24 #include "nweb_log.h"
25 #include "web_errors.h"
26
27 namespace OHOS {
28 namespace NWeb {
29 using namespace NWebError;
30
31 std::unordered_map<std::string, std::function<void(napi_env, napi_ref)>> onceType = {
32 {"webInited", RegisterWebInitedCallback},
33 };
34
WebFunctionInit(napi_env env,napi_value exports)35 napi_value WebFunctionInit(napi_env env, napi_value exports)
36 {
37 napi_property_descriptor properties[] = {
38 DECLARE_NAPI_FUNCTION("once", JsOnce),
39 };
40 napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
41 return exports;
42 }
43
JsOnce(napi_env env,napi_callback_info info)44 napi_value JsOnce(napi_env env, napi_callback_info info)
45 {
46 napi_value thisVar = nullptr;
47 napi_value result = nullptr;
48 size_t argc = INTEGER_TWO;
49 napi_value argv[INTEGER_TWO] = { 0 };
50
51 napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
52 if (argc != INTEGER_TWO) {
53 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
54 return result;
55 }
56
57 std::string type = "";
58 napi_valuetype valueType = napi_undefined;
59 napi_typeof(env, argv[INTEGER_ONE], &valueType);
60 if (!(NapiParseUtils::ParseString(env, argv[0], type)) || (onceType.find(type) == onceType.end()) ||
61 (valueType != napi_function)) {
62 BusinessError::ThrowErrorByErrcode(env, PARAM_CHECK_ERROR);
63 return result;
64 }
65 napi_ref callback = nullptr;
66 napi_create_reference(env, argv[INTEGER_ONE], 1, &callback);
67 onceType.find(type)->second(env, callback);
68
69 return result;
70 }
71
RegisterWebInitedCallback(napi_env env,napi_ref callback)72 void RegisterWebInitedCallback(napi_env env, napi_ref callback)
73 {
74 WebInitedCallbackParam *param = new (std::nothrow) WebInitedCallbackParam(env, callback);
75 if (param == nullptr) {
76 return;
77 }
78 WebRunInitedCallback *runWebInitedCallbackObj = new (std::nothrow) WebRunInitedCallbackImpl(param);
79 if (runWebInitedCallbackObj == nullptr) {
80 delete param;
81 return;
82 }
83 OhosAdapterHelper::GetInstance().GetInitWebAdapter()->SetRunWebInitedCallback(std::move(runWebInitedCallbackObj));
84 }
85 } // namespace NWeb
86 } // namespace OHOS
87