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 "webview_controller.h"
17 
18 #include <memory>
19 #include <unordered_map>
20 #include <securec.h>
21 #include <regex>
22 
23 #include "application_context.h"
24 #include "business_error.h"
25 #include "napi_parse_utils.h"
26 #include "ohos_resource_adapter_impl.h"
27 
28 #include "native_arkweb_utils.h"
29 #include "native_interface_arkweb.h"
30 #include "native_media_player_impl.h"
31 
32 #include "nweb_log.h"
33 #include "nweb_store_web_archive_callback.h"
34 #include "web_errors.h"
35 #include "webview_createpdf_execute_callback.h"
36 #include "webview_hasimage_callback.h"
37 #include "webview_javascript_execute_callback.h"
38 #include "webview_javascript_result_callback.h"
39 
40 #include "nweb_precompile_callback.h"
41 #include "nweb_cache_options_impl.h"
42 
43 #include "bundle_mgr_proxy.h"
44 #include "if_system_ability_manager.h"
45 #include "iservice_registry.h"
46 #include "parameters.h"
47 #include "system_ability_definition.h"
48 
49 namespace {
50 constexpr int32_t PARAMZERO = 0;
51 constexpr int32_t PARAMONE = 1;
52 constexpr int32_t RESULT_COUNT = 2;
53 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
54 const std::string MODULE_NAME_PREFIX = "moduleName:";
55 } // namespace
56 
57 namespace OHOS {
58 namespace NWeb {
59 namespace {
60 constexpr uint32_t URL_MAXIMUM = 2048;
GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleName)61 bool GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleName)
62 {
63     static std::string applicationBundleName;
64     static std::string applicationModuleName;
65     if (!applicationBundleName.empty() && !applicationModuleName.empty()) {
66         bundleName = applicationBundleName;
67         moduleName = applicationModuleName;
68         return true;
69     }
70     std::shared_ptr<AbilityRuntime::ApplicationContext> context =
71         AbilityRuntime::ApplicationContext::GetApplicationContext();
72     if (!context) {
73         WVLOG_E("Failed to get application context.");
74         return false;
75     }
76     auto resourceManager = context->GetResourceManager();
77     if (!resourceManager) {
78         WVLOG_E("Failed to get resource manager.");
79         return false;
80     }
81     applicationBundleName = resourceManager->bundleInfo.first;
82     applicationModuleName = resourceManager->bundleInfo.second;
83     bundleName = applicationBundleName;
84     moduleName = applicationModuleName;
85     WVLOG_D("application bundleName: %{public}s, moduleName: %{public}s", bundleName.c_str(), moduleName.c_str());
86     return true;
87 }
88 }
89 using namespace NWebError;
90 std::mutex g_objectMtx;
91 std::unordered_map<int32_t, WebviewController*> g_webview_controller_map;
92 std::string WebviewController::customeSchemeCmdLine_ = "";
93 bool WebviewController::existNweb_ = false;
94 bool WebviewController::webDebuggingAccess_ = OHOS::system::GetBoolParameter("web.debug.devtools", false);
95 std::set<std::string> WebviewController::webTagSet_;
96 int32_t WebviewController::webTagStrId_ = 0;
97 
WebviewController(int32_t nwebId)98 WebviewController::WebviewController(int32_t nwebId) : nwebId_(nwebId)
99 {
100     if (IsInit()) {
101         std::unique_lock<std::mutex> lk(g_objectMtx);
102         g_webview_controller_map.emplace(nwebId, this);
103     }
104 }
105 
WebviewController(const std::string& webTag)106 WebviewController::WebviewController(const std::string& webTag) : webTag_(webTag)
107 {
108     NWebHelper::Instance().SetWebTag(-1, webTag_.c_str());
109 }
110 
~WebviewController()111 WebviewController::~WebviewController()
112 {
113     std::unique_lock<std::mutex> lk(g_objectMtx);
114     g_webview_controller_map.erase(nwebId_);
115 }
116 
SetWebId(int32_t nwebId)117 void WebviewController::SetWebId(int32_t nwebId)
118 {
119     nwebId_ = nwebId;
120     std::unique_lock<std::mutex> lk(g_objectMtx);
121     g_webview_controller_map.emplace(nwebId, this);
122 
123     if (webTag_.empty()) {
124         WVLOG_I("native webtag is empty, don't care because it's not a native instance");
125         return;
126     }
127 
128     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
129     if (nweb_ptr) {
130         OH_NativeArkWeb_BindWebTagToWebInstance(webTag_.c_str(), nweb_ptr);
131         NWebHelper::Instance().SetWebTag(nwebId_, webTag_.c_str());
132     }
133     SetNWebJavaScriptResultCallBack();
134     NativeArkWeb_OnValidCallback validCallback = OH_NativeArkWeb_GetJavaScriptProxyValidCallback(webTag_.c_str());
135     if (validCallback) {
136         WVLOG_I("native validCallback start to call");
137         (*validCallback)(webTag_.c_str());
138     } else {
139         WVLOG_W("native validCallback is null, callback nothing");
140     }
141 }
142 
FromID(int32_t nwebId)143 WebviewController* WebviewController::FromID(int32_t nwebId)
144 {
145     std::unique_lock<std::mutex> lk(g_objectMtx);
146     if (auto it = g_webview_controller_map.find(nwebId); it != g_webview_controller_map.end()) {
147         auto control = it->second;
148         return control;
149     }
150     return nullptr;
151 }
152 
InnerCompleteWindowNew(int32_t parentNwebId)153 void WebviewController::InnerCompleteWindowNew(int32_t parentNwebId)
154 {
155     WVLOG_D("WebviewController::InnerCompleteWindowNew parentNwebId == "
156             "%{public}d ",
157         parentNwebId);
158     if (parentNwebId < 0) {
159         WVLOG_E("WebviewController::InnerCompleteWindowNew parentNwebId == %{public}d "
160                 "error",
161             parentNwebId);
162         return;
163     }
164     auto parentControl = FromID(parentNwebId);
165     if (!parentControl || !(parentControl->javaScriptResultCb_)) {
166         WVLOG_E("WebviewController::InnerCompleteWindowNew parentControl or "
167                 "javaScriptResultCb_ is null");
168         return;
169     }
170 
171     auto parNamedObjs = parentControl->javaScriptResultCb_->GetNamedObjects();
172 
173     auto currentControl = FromID(nwebId_);
174     if (!currentControl || !(currentControl->javaScriptResultCb_)) {
175         WVLOG_E("WebviewController::InnerCompleteWindowNew currentControl or "
176                 "javaScriptResultCb_ is null");
177         return;
178     }
179 
180     std::unique_lock<std::mutex> lock(webMtx_);
181     {
182         auto curNamedObjs = currentControl->javaScriptResultCb_->GetNamedObjects();
183         SetNWebJavaScriptResultCallBack();
184         for (auto it = parNamedObjs.begin(); it != parNamedObjs.end(); it++) {
185             if (curNamedObjs.find(it->first) != curNamedObjs.end()) {
186                 continue;
187             }
188             if (it->second && IsInit()) {
189                 RegisterJavaScriptProxyParam param;
190                 param.env = it->second->GetEnv();
191                 param.obj = it->second->GetValue();
192                 param.objName = it->first;
193                 param.syncMethodList = it->second->GetSyncMethodNames();
194                 param.asyncMethodList = it->second->GetAsyncMethodNames();
195                 param.permission = it->second->GetPermission();
196                 RegisterJavaScriptProxy(param);
197             }
198         }
199     }
200 }
201 
IsInit() const202 bool WebviewController::IsInit() const
203 {
204     return NWebHelper::Instance().GetNWeb(nwebId_) ? true : false;
205 }
206 
AccessForward() const207 bool WebviewController::AccessForward() const
208 {
209     bool access = false;
210     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
211     if (nweb_ptr) {
212         access = nweb_ptr->IsNavigateForwardAllowed();
213     } else {
214         WVLOG_E("WebviewController::AccessForward nweb_ptr is null");
215     }
216     return access;
217 }
218 
AccessBackward() const219 bool WebviewController::AccessBackward() const
220 {
221     bool access = false;
222     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
223     if (nweb_ptr) {
224         access = nweb_ptr->IsNavigatebackwardAllowed();
225     }
226     return access;
227 }
228 
AccessStep(int32_t step) const229 bool WebviewController::AccessStep(int32_t step) const
230 {
231     bool access = false;
232     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
233     if (nweb_ptr) {
234         access = nweb_ptr->CanNavigateBackOrForward(step);
235     }
236     return access;
237 }
238 
ClearHistory()239 void WebviewController::ClearHistory()
240 {
241     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
242     if (nweb_ptr) {
243         nweb_ptr->DeleteNavigateHistory();
244     }
245 }
246 
Forward()247 void WebviewController::Forward()
248 {
249     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
250     if (nweb_ptr) {
251         nweb_ptr->NavigateForward();
252     }
253 }
254 
Backward()255 void WebviewController::Backward()
256 {
257     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
258     if (nweb_ptr) {
259         nweb_ptr->NavigateBack();
260     }
261 }
262 
OnActive()263 void WebviewController::OnActive()
264 {
265     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
266     if (nweb_ptr) {
267         nweb_ptr->OnContinue();
268     }
269 }
270 
OnInactive()271 void WebviewController::OnInactive()
272 {
273     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
274     if (nweb_ptr) {
275         nweb_ptr->OnPause();
276     }
277 }
278 
Refresh()279 void WebviewController::Refresh()
280 {
281     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
282     if (nweb_ptr) {
283         nweb_ptr->Reload();
284     }
285 }
286 
ZoomIn()287 ErrCode WebviewController::ZoomIn()
288 {
289     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
290     if (!nweb_ptr) {
291         return INIT_ERROR;
292     }
293     ErrCode result = NWebError::NO_ERROR;
294     result = nweb_ptr->ZoomIn();
295 
296     return result;
297 }
298 
ZoomOut()299 ErrCode WebviewController::ZoomOut()
300 {
301     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
302     if (!nweb_ptr) {
303         return INIT_ERROR;
304     }
305     ErrCode result = NWebError::NO_ERROR;
306     result = nweb_ptr->ZoomOut();
307 
308     return result;
309 }
310 
GetWebId() const311 int32_t WebviewController::GetWebId() const
312 {
313     int32_t webId = -1;
314     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
315     if (nweb_ptr) {
316         webId = static_cast<int32_t>(nweb_ptr->GetWebId());
317     }
318     return webId;
319 }
320 
GetUserAgent()321 std::string WebviewController::GetUserAgent()
322 {
323     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
324     if (!nweb_ptr) {
325         return "";
326     }
327     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
328     if (!setting) {
329         return "";
330     }
331     return setting->DefaultUserAgent();
332 }
333 
GetCustomUserAgent() const334 std::string WebviewController::GetCustomUserAgent() const
335 {
336     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
337     if (!nweb_ptr) {
338         return "";
339     }
340     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
341     if (!setting) {
342         return "";
343     }
344     return setting->UserAgent();
345 }
346 
SetCustomUserAgent(const std::string& userAgent)347 ErrCode WebviewController::SetCustomUserAgent(const std::string& userAgent)
348 {
349     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
350     if (!nweb_ptr) {
351         return NWebError::INIT_ERROR;
352     }
353     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
354     if (!setting) {
355         return NWebError::INIT_ERROR;
356     }
357     setting->PutUserAgent(userAgent);
358     return NWebError::NO_ERROR;
359 }
360 
GetTitle()361 std::string WebviewController::GetTitle()
362 {
363     std::string title = "";
364     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
365     if (nweb_ptr) {
366         title = nweb_ptr->Title();
367     }
368     return title;
369 }
370 
GetPageHeight()371 int32_t WebviewController::GetPageHeight()
372 {
373     int32_t pageHeight = 0;
374     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
375     if (nweb_ptr) {
376         pageHeight = nweb_ptr->ContentHeight();
377     }
378     return pageHeight;
379 }
380 
BackOrForward(int32_t step)381 ErrCode WebviewController::BackOrForward(int32_t step)
382 {
383     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
384     if (!nweb_ptr) {
385         return INIT_ERROR;
386     }
387 
388     nweb_ptr->NavigateBackOrForward(step);
389     return NWebError::NO_ERROR;
390 }
391 
StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env, napi_ref jsCallback)392 void WebviewController::StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env,
393     napi_ref jsCallback)
394 {
395     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
396     if (!nweb_ptr) {
397         napi_value setResult[RESULT_COUNT] = {0};
398         setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
399         napi_get_null(env, &setResult[PARAMONE]);
400 
401         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
402         napi_value callback = nullptr;
403         napi_get_reference_value(env, jsCallback, &callback);
404         napi_value callbackResult = nullptr;
405         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
406         napi_delete_reference(env, jsCallback);
407         return;
408     }
409 
410     if (jsCallback == nullptr) {
411         return;
412     }
413 
414     auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
415     callbackImpl->SetCallBack([env, jCallback = std::move(jsCallback)](std::string result) {
416         if (!env) {
417             return;
418         }
419         napi_handle_scope scope = nullptr;
420         napi_open_handle_scope(env, &scope);
421         if (scope == nullptr) {
422             return;
423         }
424 
425         napi_value setResult[RESULT_COUNT] = {0};
426         if (result.empty()) {
427             setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
428             napi_get_null(env, &setResult[PARAMONE]);
429         } else {
430             napi_get_undefined(env, &setResult[PARAMZERO]);
431             napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
432         }
433         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
434         napi_value callback = nullptr;
435         napi_get_reference_value(env, jCallback, &callback);
436         napi_value callbackResult = nullptr;
437         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
438 
439         napi_delete_reference(env, jCallback);
440         napi_close_handle_scope(env, scope);
441     });
442     nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
443     return;
444 }
445 
StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env, napi_deferred deferred)446 void WebviewController::StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env,
447     napi_deferred deferred)
448 {
449     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
450     if (!nweb_ptr) {
451         napi_value jsResult = nullptr;
452         jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
453         napi_reject_deferred(env, deferred, jsResult);
454         return;
455     }
456 
457     if (deferred == nullptr) {
458         return;
459     }
460 
461     auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
462     callbackImpl->SetCallBack([env, deferred](std::string result) {
463         if (!env) {
464             return;
465         }
466         napi_handle_scope scope = nullptr;
467         napi_open_handle_scope(env, &scope);
468         if (scope == nullptr) {
469             return;
470         }
471 
472         napi_value setResult[RESULT_COUNT] = {0};
473         setResult[PARAMZERO] = NWebError::BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
474         napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
475         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
476         if (!result.empty()) {
477             napi_resolve_deferred(env, deferred, args[PARAMONE]);
478         } else {
479             napi_reject_deferred(env, deferred, args[PARAMZERO]);
480         }
481         napi_close_handle_scope(env, scope);
482     });
483     nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
484     return;
485 }
486 
CreateWebMessagePorts()487 std::vector<std::string> WebviewController::CreateWebMessagePorts()
488 {
489     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
490     if (!nweb_ptr) {
491         std::vector<std::string> empty;
492         return empty;
493     }
494 
495     return nweb_ptr->CreateWebMessagePorts();
496 }
497 
PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl)498 ErrCode WebviewController::PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl)
499 {
500     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
501     if (!nweb_ptr) {
502         return INIT_ERROR;
503     }
504 
505     nweb_ptr->PostWebMessage(message, ports, targetUrl);
506     return NWebError::NO_ERROR;
507 }
508 
WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType)509 WebMessagePort::WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType)
510     : nwebId_(nwebId), portHandle_(port), isExtentionType_(isExtentionType)
511 {}
512 
ClosePort()513 ErrCode WebMessagePort::ClosePort()
514 {
515     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
516     if (!nweb_ptr) {
517         return INIT_ERROR;
518     }
519 
520     nweb_ptr->ClosePort(portHandle_);
521     portHandle_.clear();
522     return NWebError::NO_ERROR;
523 }
524 
PostPortMessage(std::shared_ptr<NWebMessage> data)525 ErrCode WebMessagePort::PostPortMessage(std::shared_ptr<NWebMessage> data)
526 {
527     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
528     if (!nweb_ptr) {
529         return INIT_ERROR;
530     }
531 
532     if (portHandle_.empty()) {
533         WVLOG_E("can't post message, message port already closed");
534         return CAN_NOT_POST_MESSAGE;
535     }
536     nweb_ptr->PostPortMessage(portHandle_, data);
537     return NWebError::NO_ERROR;
538 }
539 
SetPortMessageCallback( std::shared_ptr<NWebMessageValueCallback> callback)540 ErrCode WebMessagePort::SetPortMessageCallback(
541     std::shared_ptr<NWebMessageValueCallback> callback)
542 {
543     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
544     if (!nweb_ptr) {
545         return INIT_ERROR;
546     }
547 
548     if (portHandle_.empty()) {
549         WVLOG_E("can't register message port callback event, message port already closed");
550         return CAN_NOT_REGISTER_MESSAGE_EVENT;
551     }
552     nweb_ptr->SetPortMessageCallback(portHandle_, callback);
553     return NWebError::NO_ERROR;
554 }
555 
GetPortHandle() const556 std::string WebMessagePort::GetPortHandle() const
557 {
558     return portHandle_;
559 }
560 
GetHitTestValue()561 std::shared_ptr<HitTestResult> WebviewController::GetHitTestValue()
562 {
563     std::shared_ptr<HitTestResult> nwebResult;
564     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
565     if (nweb_ptr) {
566         nwebResult = nweb_ptr->GetHitTestResult();
567         if (nwebResult) {
568             nwebResult->SetType(ConverToWebHitTestType(nwebResult->GetType()));
569         }
570     }
571     return nwebResult;
572 }
573 
RequestFocus()574 void WebviewController::RequestFocus()
575 {
576     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
577     if (nweb_ptr) {
578         nweb_ptr->OnFocus();
579     }
580 }
581 
GenerateWebTag()582 std::string WebviewController::GenerateWebTag()
583 {
584     std::string webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
585     while (WebviewController::webTagSet_.find(webTag) != WebviewController::webTagSet_.end()) {
586         WebviewController::webTagStrId_++;
587         webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
588     }
589     return webTag;
590 }
591 
GetRawFileUrl(const std::string &fileName, const std::string& bundleName, const std::string& moduleName, std::string &result) const592 bool WebviewController::GetRawFileUrl(const std::string &fileName,
593     const std::string& bundleName, const std::string& moduleName, std::string &result) const
594 {
595     if (fileName.empty()) {
596         WVLOG_E("File name is empty.");
597         return false;
598     }
599     if (hapPath_.empty()) {
600         std::shared_ptr<AbilityRuntime::ApplicationContext> context =
601             AbilityRuntime::ApplicationContext::GetApplicationContext();
602         std::string packagePath = "file:///" + context->GetBundleCodeDir() + "/";
603         std::string contextBundleName = context->GetBundleName() + "/";
604         std::shared_ptr<AppExecFwk::ApplicationInfo> appInfo = context->GetApplicationInfo();
605         std::string entryDir = appInfo->entryDir;
606         bool isStage = entryDir.find("entry") == std::string::npos ? false : true;
607         result = isStage ? packagePath + "entry/resources/rawfile/" + fileName :
608             packagePath + contextBundleName + "assets/entry/resources/rawfile/" + fileName;
609     } else {
610         std::string appBundleName;
611         std::string appModuleName;
612         result = "resource://RAWFILE/";
613         if (!bundleName.empty() && !moduleName.empty() &&
614             GetAppBundleNameAndModuleName(appBundleName, appModuleName)) {
615             if (appBundleName != bundleName || appModuleName != moduleName) {
616                 result += BUNDLE_NAME_PREFIX + bundleName + "/" + MODULE_NAME_PREFIX + moduleName + "/";
617             }
618         }
619         result += fileName;
620     }
621     WVLOG_D("The parsed url is: ***");
622     return true;
623 }
624 
ParseUrl(napi_env env, napi_value urlObj, std::string& result) const625 bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result) const
626 {
627     napi_valuetype valueType = napi_null;
628     napi_typeof(env, urlObj, &valueType);
629     if ((valueType != napi_object) && (valueType != napi_string)) {
630         WVLOG_E("Unable to parse url object.");
631         return false;
632     }
633     if (valueType == napi_string) {
634         NapiParseUtils::ParseString(env, urlObj, result);
635         WVLOG_D("The parsed url is: ***");
636         return true;
637     }
638     napi_value type = nullptr;
639     napi_valuetype typeVlueType = napi_null;
640     napi_get_named_property(env, urlObj, "type", &type);
641     napi_typeof(env, type, &typeVlueType);
642     if (typeVlueType == napi_number) {
643         int32_t typeInteger;
644         NapiParseUtils::ParseInt32(env, type, typeInteger);
645         if (typeInteger == static_cast<int>(ResourceType::RAWFILE)) {
646             return ParseRawFileUrl(env, urlObj, result);
647         } else if (typeInteger == static_cast<int>(ResourceType::STRING)) {
648             if (!GetResourceUrl(env, urlObj, result)) {
649                 WVLOG_E("Unable to parse string from url object.");
650                 return false;
651             }
652             return true;
653         }
654         WVLOG_E("The type parsed from url object is not RAWFILE.");
655         return false;
656     }
657     WVLOG_E("Unable to parse type from url object.");
658     return false;
659 }
660 
ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const661 bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const
662 {
663     napi_value paraArray = nullptr;
664     napi_get_named_property(env, urlObj, "params", &paraArray);
665     bool isArray = false;
666     napi_is_array(env, paraArray, &isArray);
667     if (!isArray) {
668         WVLOG_E("Unable to parse parameter array from url object.");
669         return false;
670     }
671     napi_value fileNameObj;
672     napi_value bundleNameObj;
673     napi_value moduleNameObj;
674     std::string fileName;
675     std::string bundleName;
676     std::string moduleName;
677     napi_get_element(env, paraArray, 0, &fileNameObj);
678     napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj);
679     napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj);
680     NapiParseUtils::ParseString(env, fileNameObj, fileName);
681     NapiParseUtils::ParseString(env, bundleNameObj, bundleName);
682     NapiParseUtils::ParseString(env, moduleNameObj, moduleName);
683     return GetRawFileUrl(fileName, bundleName, moduleName, result);
684 }
685 
GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const686 bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const
687 {
688     napi_value resIdObj = nullptr;
689     napi_value bundleNameObj = nullptr;
690     napi_value moduleNameObj = nullptr;
691 
692     int32_t resId;
693     std::string bundleName;
694     std::string moduleName;
695 
696     if ((napi_get_named_property(env, urlObj, "id", &resIdObj) != napi_ok) ||
697         (napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj) != napi_ok) ||
698         (napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj) != napi_ok)) {
699         return false;
700     }
701 
702     if (!NapiParseUtils::ParseInt32(env, resIdObj, resId) ||
703         !NapiParseUtils::ParseString(env, bundleNameObj, bundleName) ||
704         !NapiParseUtils::ParseString(env, moduleNameObj, moduleName)) {
705         return false;
706     }
707 
708     if (OhosResourceAdapterImpl::GetResourceString(bundleName, moduleName, resId, result)) {
709         return true;
710     }
711     return false;
712 }
713 
PostUrl(std::string& url, std::vector<char>& postData)714 ErrCode WebviewController::PostUrl(std::string& url, std::vector<char>& postData)
715 {
716     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
717     if (!nweb_ptr) {
718         return INIT_ERROR;
719     }
720     return nweb_ptr->PostUrl(url, postData);
721 }
722 
LoadUrl(std::string url)723 ErrCode WebviewController::LoadUrl(std::string url)
724 {
725     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
726     if (!nweb_ptr) {
727         return INIT_ERROR;
728     }
729     return nweb_ptr->Load(url);
730 }
731 
LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders)732 ErrCode WebviewController::LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders)
733 {
734     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
735     if (!nweb_ptr) {
736         return INIT_ERROR;
737     }
738     return nweb_ptr->Load(url, httpHeaders);
739 }
740 
LoadData(std::string data, std::string mimeType, std::string encoding, std::string baseUrl, std::string historyUrl)741 ErrCode WebviewController::LoadData(std::string data, std::string mimeType, std::string encoding,
742     std::string baseUrl, std::string historyUrl)
743 {
744     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
745     if (!nweb_ptr) {
746         return INIT_ERROR;
747     }
748     if (baseUrl.empty() && historyUrl.empty()) {
749         return nweb_ptr->LoadWithData(data, mimeType, encoding);
750     }
751     return nweb_ptr->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
752 }
753 
ConverToWebHitTestType(int hitType)754 int WebviewController::ConverToWebHitTestType(int hitType)
755 {
756     WebHitTestType webHitType;
757     switch (hitType) {
758         case HitTestResult::UNKNOWN_TYPE:
759             webHitType = WebHitTestType::UNKNOWN;
760             break;
761         case HitTestResult::ANCHOR_TYPE:
762             webHitType = WebHitTestType::HTTP;
763             break;
764         case HitTestResult::PHONE_TYPE:
765             webHitType = WebHitTestType::PHONE;
766             break;
767         case HitTestResult::GEO_TYPE:
768             webHitType = WebHitTestType::MAP;
769             break;
770         case HitTestResult::EMAIL_TYPE:
771             webHitType = WebHitTestType::EMAIL;
772             break;
773         case HitTestResult::IMAGE_TYPE:
774             webHitType = WebHitTestType::IMG;
775             break;
776         case HitTestResult::IMAGE_ANCHOR_TYPE:
777             webHitType = WebHitTestType::HTTP_IMG;
778             break;
779         case HitTestResult::SRC_ANCHOR_TYPE:
780             webHitType = WebHitTestType::HTTP;
781             break;
782         case HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
783             webHitType = WebHitTestType::HTTP_IMG;
784             break;
785         case HitTestResult::EDIT_TEXT_TYPE:
786             webHitType = WebHitTestType::EDIT;
787             break;
788         default:
789             webHitType = WebHitTestType::UNKNOWN;
790             break;
791     }
792     return static_cast<int>(webHitType);
793 }
794 
GetHitTest()795 int WebviewController::GetHitTest()
796 {
797     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
798     if (nweb_ptr) {
799         std::shared_ptr<HitTestResult> nwebResult = nweb_ptr->GetHitTestResult();
800         if (nwebResult) {
801             return ConverToWebHitTestType(nwebResult->GetType());
802         } else {
803             return ConverToWebHitTestType(HitTestResult::UNKNOWN_TYPE);
804         }
805     }
806     return static_cast<int>(WebHitTestType::UNKNOWN);
807 }
808 
809 
ClearMatches()810 void WebviewController::ClearMatches()
811 {
812     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
813     if (nweb_ptr) {
814         nweb_ptr->ClearMatches();
815     }
816 }
817 
SearchNext(bool forward)818 void WebviewController::SearchNext(bool forward)
819 {
820     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
821     if (nweb_ptr) {
822         nweb_ptr->FindNext(forward);
823     }
824 }
825 
EnableSafeBrowsing(bool enable)826 void WebviewController::EnableSafeBrowsing(bool enable)
827 {
828     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
829     if (nweb_ptr) {
830         nweb_ptr->EnableSafeBrowsing(enable);
831     }
832 }
833 
IsSafeBrowsingEnabled() const834 bool WebviewController::IsSafeBrowsingEnabled() const
835 {
836     bool isSafeBrowsingEnabled = false;
837     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
838     if (nweb_ptr) {
839         isSafeBrowsingEnabled = nweb_ptr->IsSafeBrowsingEnabled();
840     }
841     return isSafeBrowsingEnabled;
842 }
843 
SearchAllAsync(const std::string& searchString)844 void WebviewController::SearchAllAsync(const std::string& searchString)
845 {
846     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
847     if (nweb_ptr) {
848         nweb_ptr->FindAllAsync(searchString);
849     }
850 }
851 
ClearSslCache()852 void WebviewController::ClearSslCache()
853 {
854     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
855     if (nweb_ptr) {
856         nweb_ptr->ClearSslCache();
857     }
858 }
859 
ClearClientAuthenticationCache()860 void WebviewController::ClearClientAuthenticationCache()
861 {
862     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
863     if (nweb_ptr) {
864         nweb_ptr->ClearClientAuthenticationCache();
865     }
866 }
867 
Stop()868 void WebviewController::Stop()
869 {
870     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
871     if (nweb_ptr) {
872         nweb_ptr->Stop();
873     }
874 }
875 
Zoom(float factor)876 ErrCode WebviewController::Zoom(float factor)
877 {
878     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
879     if (!nweb_ptr) {
880         return INIT_ERROR;
881     }
882     ErrCode result = NWebError::NO_ERROR;
883     result = nweb_ptr->Zoom(factor);
884 
885     return result;
886 }
887 
DeleteJavaScriptRegister(const std::string& objName, const std::vector<std::string>& methodList)888 ErrCode WebviewController::DeleteJavaScriptRegister(const std::string& objName,
889     const std::vector<std::string>& methodList)
890 {
891     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
892     if (nweb_ptr) {
893         nweb_ptr->UnregisterArkJSfunction(objName, methodList);
894     }
895 
896     if (javaScriptResultCb_) {
897         bool ret = javaScriptResultCb_->DeleteJavaScriptRegister(objName);
898         if (!ret) {
899             return CANNOT_DEL_JAVA_SCRIPT_PROXY;
900         }
901     }
902 
903     return NWebError::NO_ERROR;
904 }
905 
SetNWebJavaScriptResultCallBack()906 void WebviewController::SetNWebJavaScriptResultCallBack()
907 {
908     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
909     if (!nweb_ptr) {
910         return;
911     }
912 
913     if (javaScriptResultCb_ && (javaScriptResultCb_->GetNWebId() == nwebId_)) {
914         return;
915     }
916 
917     javaScriptResultCb_ = std::make_shared<WebviewJavaScriptResultCallBack>(nwebId_);
918     nweb_ptr->SetNWebJavaScriptResultCallBack(javaScriptResultCb_);
919 }
920 
RegisterJavaScriptProxy(RegisterJavaScriptProxyParam& param)921 void WebviewController::RegisterJavaScriptProxy(RegisterJavaScriptProxyParam& param)
922 {
923     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
924     if (!nweb_ptr) {
925         WVLOG_E("WebviewController::RegisterJavaScriptProxy nweb_ptr is null");
926         return;
927     }
928     JavaScriptOb::ObjectID objId =
929         static_cast<JavaScriptOb::ObjectID>(JavaScriptOb::JavaScriptObjIdErrorCode::WEBCONTROLLERERROR);
930 
931     if (!javaScriptResultCb_) {
932         WVLOG_E("WebviewController::RegisterJavaScriptProxy javaScriptResultCb_ is "
933                 "null");
934         return;
935     }
936 
937     if (param.syncMethodList.empty() && param.asyncMethodList.empty()) {
938         WVLOG_E("WebviewController::RegisterJavaScriptProxy all methodList are "
939                 "empty");
940         return;
941     }
942 
943     std::vector<std::string> allMethodList;
944     std::merge(param.syncMethodList.begin(), param.syncMethodList.end(),
945                param.asyncMethodList.begin(), param.asyncMethodList.end(),
946                std::back_inserter(allMethodList));
947 
948     RegisterJavaScriptProxyParam param_tmp;
949     param_tmp.env = param.env;
950     param_tmp.obj = param.obj;
951     param_tmp.objName = param.objName;
952     param_tmp.syncMethodList = allMethodList;
953     param_tmp.asyncMethodList = param.asyncMethodList;
954     param_tmp.permission = param.permission;
955     objId = javaScriptResultCb_->RegisterJavaScriptProxy(param_tmp);
956 
957     nweb_ptr->RegisterArkJSfunction(param_tmp.objName, param_tmp.syncMethodList,
958                                     std::vector<std::string>(), objId, param_tmp.permission);
959 }
960 
RunJavaScriptCallback( const std::string& script, napi_env env, napi_ref jsCallback, bool extention)961 void WebviewController::RunJavaScriptCallback(
962     const std::string& script, napi_env env, napi_ref jsCallback, bool extention)
963 {
964     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
965     if (!nweb_ptr) {
966         napi_value setResult[RESULT_COUNT] = {0};
967         setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
968         napi_get_null(env, &setResult[PARAMONE]);
969 
970         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
971         napi_value callback = nullptr;
972         napi_get_reference_value(env, jsCallback, &callback);
973         napi_value callbackResult = nullptr;
974         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
975         napi_delete_reference(env, jsCallback);
976         return;
977     }
978 
979     if (jsCallback == nullptr) {
980         return;
981     }
982 
983     auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
984     nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
985 }
986 
RunJavaScriptPromise(const std::string &script, napi_env env, napi_deferred deferred, bool extention)987 void WebviewController::RunJavaScriptPromise(const std::string &script, napi_env env,
988     napi_deferred deferred, bool extention)
989 {
990     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
991     if (!nweb_ptr) {
992         napi_value jsResult = nullptr;
993         jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
994         napi_reject_deferred(env, deferred, jsResult);
995         return;
996     }
997 
998     if (deferred == nullptr) {
999         return;
1000     }
1001 
1002     auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
1003     nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
1004 }
1005 
RunJavaScriptCallbackExt( const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention)1006 void WebviewController::RunJavaScriptCallbackExt(
1007     const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention)
1008 {
1009     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1010     if (!nweb_ptr) {
1011         napi_value setResult[RESULT_COUNT] = {0};
1012         setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1013         napi_get_null(env, &setResult[PARAMONE]);
1014 
1015         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1016         napi_value callback = nullptr;
1017         napi_get_reference_value(env, jsCallback, &callback);
1018         napi_value callbackResult = nullptr;
1019         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1020         napi_delete_reference(env, jsCallback);
1021         close(fd);
1022         return;
1023     }
1024 
1025     if (jsCallback == nullptr) {
1026         close(fd);
1027         return;
1028     }
1029 
1030     auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
1031     nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
1032 }
1033 
RunJavaScriptPromiseExt( const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention)1034 void WebviewController::RunJavaScriptPromiseExt(
1035     const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention)
1036 {
1037     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1038     if (!nweb_ptr) {
1039         napi_value jsResult = nullptr;
1040         jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1041         napi_reject_deferred(env, deferred, jsResult);
1042         close(fd);
1043         return;
1044     }
1045 
1046     if (deferred == nullptr) {
1047         close(fd);
1048         return;
1049     }
1050 
1051     auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
1052     nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
1053 }
1054 
CreatePDFCallbackExt( napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_ref pdfCallback)1055 void WebviewController::CreatePDFCallbackExt(
1056     napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_ref pdfCallback)
1057 {
1058     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1059     if (!nweb_ptr) {
1060         napi_value setResult[RESULT_COUNT] = { 0 };
1061         setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1062         napi_get_null(env, &setResult[PARAMONE]);
1063 
1064         napi_value args[RESULT_COUNT] = { setResult[PARAMZERO], setResult[PARAMONE] };
1065         napi_value callback = nullptr;
1066         napi_get_reference_value(env, pdfCallback, &callback);
1067         napi_value callbackResult = nullptr;
1068         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1069         napi_delete_reference(env, pdfCallback);
1070         return;
1071     }
1072     if (pdfCallback == nullptr) {
1073         return;
1074     }
1075     auto callbackImpl = std::make_shared<WebviewCreatePDFExecuteCallback>(env, pdfCallback, nullptr);
1076     nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl);
1077 }
1078 
CreatePDFPromiseExt( napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_deferred deferred)1079 void WebviewController::CreatePDFPromiseExt(
1080     napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_deferred deferred)
1081 {
1082     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1083     if (!nweb_ptr) {
1084         napi_value pdfResult = nullptr;
1085         pdfResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1086         napi_reject_deferred(env, deferred, pdfResult);
1087         return;
1088     }
1089     if (deferred == nullptr) {
1090         return;
1091     }
1092     auto callbackImpl = std::make_shared<WebviewCreatePDFExecuteCallback>(env, nullptr, deferred);
1093     nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl);
1094 }
1095 
GetUrl()1096 std::string WebviewController::GetUrl()
1097 {
1098     std::string url = "";
1099     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1100     if (nweb_ptr) {
1101         url = nweb_ptr->GetUrl();
1102     }
1103     return url;
1104 }
1105 
GetOriginalUrl()1106 std::string WebviewController::GetOriginalUrl()
1107 {
1108     std::string url = "";
1109     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1110     if (nweb_ptr) {
1111         url = nweb_ptr->GetOriginalUrl();
1112     }
1113     return url;
1114 }
1115 
TerminateRenderProcess() const1116 bool WebviewController::TerminateRenderProcess() const
1117 {
1118     bool ret = false;
1119     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1120     if (nweb_ptr) {
1121         ret = nweb_ptr->TerminateRenderProcess();
1122     }
1123     return ret;
1124 }
1125 
PutNetworkAvailable(bool available)1126 void WebviewController::PutNetworkAvailable(bool available)
1127 {
1128     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1129     if (nweb_ptr) {
1130         nweb_ptr->PutNetworkAvailable(available);
1131     }
1132 }
1133 
HasImagesCallback(napi_env env, napi_ref jsCallback)1134 ErrCode WebviewController::HasImagesCallback(napi_env env, napi_ref jsCallback)
1135 {
1136     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1137     if (!nweb_ptr) {
1138         napi_value setResult[RESULT_COUNT] = {0};
1139         setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1140         napi_get_null(env, &setResult[PARAMONE]);
1141 
1142         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1143         napi_value callback = nullptr;
1144         napi_get_reference_value(env, jsCallback, &callback);
1145         napi_value callbackResult = nullptr;
1146         napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1147         napi_delete_reference(env, jsCallback);
1148         return NWebError::INIT_ERROR;
1149     }
1150 
1151     if (jsCallback == nullptr) {
1152         return NWebError::PARAM_CHECK_ERROR;
1153     }
1154 
1155     auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, jsCallback, nullptr);
1156     nweb_ptr->HasImages(callbackImpl);
1157     return NWebError::NO_ERROR;
1158 }
1159 
HasImagesPromise(napi_env env, napi_deferred deferred)1160 ErrCode WebviewController::HasImagesPromise(napi_env env, napi_deferred deferred)
1161 {
1162     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1163     if (!nweb_ptr) {
1164         napi_value jsResult = nullptr;
1165         jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1166         napi_reject_deferred(env, deferred, jsResult);
1167         return NWebError::INIT_ERROR;
1168     }
1169 
1170     if (deferred == nullptr) {
1171         return NWebError::PARAM_CHECK_ERROR;
1172     }
1173 
1174     auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, nullptr, deferred);
1175     nweb_ptr->HasImages(callbackImpl);
1176     return NWebError::NO_ERROR;
1177 }
1178 
RemoveCache(bool includeDiskFiles)1179 void WebviewController::RemoveCache(bool includeDiskFiles)
1180 {
1181     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1182     if (nweb_ptr) {
1183         nweb_ptr->RemoveCache(includeDiskFiles);
1184     }
1185 }
1186 
GetHistoryList()1187 std::shared_ptr<NWebHistoryList> WebviewController::GetHistoryList()
1188 {
1189     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1190     if (!nweb_ptr) {
1191         return nullptr;
1192     }
1193     return nweb_ptr->GetHistoryList();
1194 }
1195 
GetItem(int32_t index)1196 std::shared_ptr<NWebHistoryItem> WebHistoryList::GetItem(int32_t index)
1197 {
1198     if (!sptrHistoryList_) {
1199         return nullptr;
1200     }
1201     return sptrHistoryList_->GetItem(index);
1202 }
1203 
GetListSize()1204 int32_t WebHistoryList::GetListSize()
1205 {
1206     int32_t listSize = 0;
1207 
1208     if (!sptrHistoryList_) {
1209         return listSize;
1210     }
1211     listSize = sptrHistoryList_->GetListSize();
1212     return listSize;
1213 }
1214 
GetFavicon( const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const1215 bool WebviewController::GetFavicon(
1216     const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const
1217 {
1218     bool isGetFavicon = false;
1219     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1220     if (nweb_ptr) {
1221         isGetFavicon = nweb_ptr->GetFavicon(data, width, height, colorType, alphaType);
1222     }
1223     return isGetFavicon;
1224 }
1225 
SerializeWebState()1226 std::vector<uint8_t> WebviewController::SerializeWebState()
1227 {
1228     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1229     if (nweb_ptr) {
1230         return nweb_ptr->SerializeWebState();
1231     }
1232     std::vector<uint8_t> empty;
1233     return empty;
1234 }
1235 
RestoreWebState(const std::vector<uint8_t> &state) const1236 bool WebviewController::RestoreWebState(const std::vector<uint8_t> &state) const
1237 {
1238     bool isRestored = false;
1239     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1240     if (nweb_ptr) {
1241         isRestored = nweb_ptr->RestoreWebState(state);
1242     }
1243     return isRestored;
1244 }
1245 
ScrollPageDown(bool bottom)1246 void WebviewController::ScrollPageDown(bool bottom)
1247 {
1248     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1249     if (nweb_ptr) {
1250         nweb_ptr->PageDown(bottom);
1251     }
1252     return;
1253 }
1254 
ScrollPageUp(bool top)1255 void WebviewController::ScrollPageUp(bool top)
1256 {
1257     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1258     if (nweb_ptr) {
1259         nweb_ptr->PageUp(top);
1260     }
1261     return;
1262 }
1263 
ScrollTo(float x, float y)1264 void WebviewController::ScrollTo(float x, float y)
1265 {
1266     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1267     if (nweb_ptr) {
1268         nweb_ptr->ScrollTo(x, y);
1269     }
1270     return;
1271 }
1272 
ScrollBy(float deltaX, float deltaY)1273 void WebviewController::ScrollBy(float deltaX, float deltaY)
1274 {
1275     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1276     if (nweb_ptr) {
1277         nweb_ptr->ScrollBy(deltaX, deltaY);
1278     }
1279     return;
1280 }
1281 
SlideScroll(float vx, float vy)1282 void WebviewController::SlideScroll(float vx, float vy)
1283 {
1284     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1285     if (nweb_ptr) {
1286         nweb_ptr->SlideScroll(vx, vy);
1287     }
1288     return;
1289 }
1290 
SetScrollable(bool enable)1291 void WebviewController::SetScrollable(bool enable)
1292 {
1293     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1294     if (!nweb_ptr) {
1295         return;
1296     }
1297     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1298     if (!setting) {
1299         return;
1300     }
1301     return setting->SetScrollable(enable);
1302 }
1303 
GetScrollable() const1304 bool WebviewController::GetScrollable() const
1305 {
1306     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1307     if (!nweb_ptr) {
1308         return true;
1309     }
1310     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1311     if (!setting) {
1312         return true;
1313     }
1314     return setting->GetScrollable();
1315 }
1316 
InnerSetHapPath(const std::string &hapPath)1317 void WebviewController::InnerSetHapPath(const std::string &hapPath)
1318 {
1319     hapPath_ = hapPath;
1320 }
1321 
GetCertChainDerData(std::vector<std::string> &certChainDerData) const1322 bool WebviewController::GetCertChainDerData(std::vector<std::string> &certChainDerData) const
1323 {
1324     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1325     if (!nweb_ptr) {
1326         WVLOG_E("GetCertChainDerData failed, nweb ptr is null");
1327         return false;
1328     }
1329 
1330     return nweb_ptr->GetCertChainDerData(certChainDerData, true);
1331 }
1332 
SetAudioMuted(bool muted)1333 ErrCode WebviewController::SetAudioMuted(bool muted)
1334 {
1335     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1336     if (!nweb_ptr) {
1337         return NWebError::INIT_ERROR;
1338     }
1339 
1340     nweb_ptr->SetAudioMuted(muted);
1341     return NWebError::NO_ERROR;
1342 }
1343 
PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders)1344 ErrCode WebviewController::PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders)
1345 {
1346     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1347     if (!nweb_ptr) {
1348         return NWebError::INIT_ERROR;
1349     }
1350 
1351     nweb_ptr->PrefetchPage(url, additionalHttpHeaders);
1352     return NWebError::NO_ERROR;
1353 }
1354 
OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs, const PrintAttributesAdapter& newAttrs, uint32_t fd, std::function<void(std::string, uint32_t)> writeResultCallback)1355 void WebPrintDocument::OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs,
1356     const PrintAttributesAdapter& newAttrs, uint32_t fd, std::function<void(std::string, uint32_t)> writeResultCallback)
1357 {
1358     if (printDocAdapter_) {
1359         std::shared_ptr<PrintWriteResultCallbackAdapter> callback =
1360             std::make_shared<WebPrintWriteResultCallbackAdapter>(writeResultCallback);
1361         printDocAdapter_->OnStartLayoutWrite(jobId, oldAttrs, newAttrs, fd, callback);
1362     }
1363 }
1364 
OnJobStateChanged(const std::string& jobId, uint32_t state)1365 void WebPrintDocument::OnJobStateChanged(const std::string& jobId, uint32_t state)
1366 {
1367     if (printDocAdapter_) {
1368         printDocAdapter_->OnJobStateChanged(jobId, state);
1369     }
1370 }
1371 
CreateWebPrintDocumentAdapter(const std::string& jobName)1372 void* WebviewController::CreateWebPrintDocumentAdapter(const std::string& jobName)
1373 {
1374     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1375     if (!nweb_ptr) {
1376         return nullptr;
1377     }
1378     return nweb_ptr->CreateWebPrintDocumentAdapter(jobName);
1379 }
1380 
CloseAllMediaPresentations()1381 void WebviewController::CloseAllMediaPresentations()
1382 {
1383     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1384     if (nweb_ptr) {
1385         nweb_ptr->CloseAllMediaPresentations();
1386     }
1387 }
1388 
StopAllMedia()1389 void WebviewController::StopAllMedia()
1390 {
1391     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1392     if (nweb_ptr) {
1393         nweb_ptr->StopAllMedia();
1394     }
1395 }
1396 
ResumeAllMedia()1397 void WebviewController::ResumeAllMedia()
1398 {
1399     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1400     if (nweb_ptr) {
1401         nweb_ptr->ResumeAllMedia();
1402     }
1403 }
1404 
PauseAllMedia()1405 void WebviewController::PauseAllMedia()
1406 {
1407     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1408     if (nweb_ptr) {
1409         nweb_ptr->PauseAllMedia();
1410     }
1411 }
1412 
GetMediaPlaybackState()1413 int WebviewController::GetMediaPlaybackState()
1414 {
1415     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1416     if (!nweb_ptr) {
1417         return static_cast<int>(MediaPlaybackState::NONE);
1418     }
1419     return nweb_ptr->GetMediaPlaybackState();
1420 }
1421 
GetSecurityLevel()1422 int WebviewController::GetSecurityLevel()
1423 {
1424     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1425     if (!nweb_ptr) {
1426         return static_cast<int>(SecurityLevel::NONE);
1427     }
1428 
1429     int nwebSecurityLevel = nweb_ptr->GetSecurityLevel();
1430     SecurityLevel securityLevel;
1431     switch (nwebSecurityLevel) {
1432         case static_cast<int>(CoreSecurityLevel::NONE):
1433             securityLevel = SecurityLevel::NONE;
1434             break;
1435         case static_cast<int>(CoreSecurityLevel::SECURE):
1436             securityLevel = SecurityLevel::SECURE;
1437             break;
1438         case static_cast<int>(CoreSecurityLevel::WARNING):
1439             securityLevel = SecurityLevel::WARNING;
1440             break;
1441         case static_cast<int>(CoreSecurityLevel::DANGEROUS):
1442             securityLevel = SecurityLevel::DANGEROUS;
1443             break;
1444         default:
1445             securityLevel = SecurityLevel::NONE;
1446             break;
1447     }
1448 
1449     return static_cast<int>(securityLevel);
1450 }
1451 
IsIncognitoMode() const1452 bool WebviewController::IsIncognitoMode() const
1453 {
1454     bool incognitoMode = false;
1455     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1456     if (nweb_ptr) {
1457         incognitoMode = nweb_ptr->IsIncognitoMode();
1458     }
1459     return incognitoMode;
1460 }
1461 
SetPrintBackground(bool enable)1462 void WebviewController::SetPrintBackground(bool enable)
1463 {
1464     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1465     if (nweb_ptr) {
1466         nweb_ptr->SetPrintBackground(enable);
1467     }
1468 }
1469 
GetPrintBackground() const1470 bool  WebviewController::GetPrintBackground() const
1471 {
1472     bool printBackgroundEnabled = false;
1473     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1474     if (nweb_ptr) {
1475         printBackgroundEnabled = nweb_ptr->GetPrintBackground();
1476     }
1477 
1478     return printBackgroundEnabled;
1479 }
1480 
EnableIntelligentTrackingPrevention(bool enable)1481 void WebviewController::EnableIntelligentTrackingPrevention(bool enable)
1482 {
1483     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1484     if (nweb_ptr) {
1485         nweb_ptr->EnableIntelligentTrackingPrevention(enable);
1486     }
1487 }
1488 
IsIntelligentTrackingPreventionEnabled() const1489 bool WebviewController::IsIntelligentTrackingPreventionEnabled() const
1490 {
1491     bool enabled = false;
1492     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1493     if (nweb_ptr) {
1494         enabled = nweb_ptr->IsIntelligentTrackingPreventionEnabled();
1495     }
1496     return enabled;
1497 }
1498 
WriteResultCallback(std::string jobId, uint32_t code)1499 void WebPrintWriteResultCallbackAdapter::WriteResultCallback(std::string jobId, uint32_t code)
1500 {
1501     cb_(jobId, code);
1502 }
1503 
SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const1504 bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const
1505 {
1506     if (!handler || !scheme) {
1507         WVLOG_E("WebviewController::SetWebSchemeHandler handler or scheme is nullptr");
1508         return false;
1509     }
1510     ArkWeb_SchemeHandler* schemeHandler =
1511         const_cast<ArkWeb_SchemeHandler*>(WebSchemeHandler::GetArkWebSchemeHandler(handler));
1512     return OH_ArkWeb_SetSchemeHandler(scheme, webTag_.c_str(), schemeHandler);
1513 }
1514 
ClearWebSchemeHandler()1515 int32_t WebviewController::ClearWebSchemeHandler()
1516 {
1517     return OH_ArkWeb_ClearSchemeHandlers(webTag_.c_str());
1518 }
1519 
SetWebServiveWorkerSchemeHandler( const char* scheme, WebSchemeHandler* handler)1520 bool WebviewController::SetWebServiveWorkerSchemeHandler(
1521     const char* scheme, WebSchemeHandler* handler)
1522 {
1523     ArkWeb_SchemeHandler* schemeHandler =
1524         const_cast<ArkWeb_SchemeHandler*>(WebSchemeHandler::GetArkWebSchemeHandler(handler));
1525     return OH_ArkWebServiceWorker_SetSchemeHandler(scheme, schemeHandler);
1526 }
1527 
ClearWebServiceWorkerSchemeHandler()1528 int32_t WebviewController::ClearWebServiceWorkerSchemeHandler()
1529 {
1530     return OH_ArkWebServiceWorker_ClearSchemeHandlers();
1531 }
1532 
StartCamera()1533 ErrCode WebviewController::StartCamera()
1534 {
1535     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1536     if (!nweb_ptr) {
1537         return NWebError::INIT_ERROR;
1538     }
1539 
1540     nweb_ptr->StartCamera();
1541     return NWebError::NO_ERROR;
1542 }
1543 
StopCamera()1544 ErrCode WebviewController::StopCamera()
1545 {
1546     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1547     if (!nweb_ptr) {
1548         return NWebError::INIT_ERROR;
1549     }
1550 
1551     nweb_ptr->StopCamera();
1552     return NWebError::NO_ERROR;
1553 }
1554 
CloseCamera()1555 ErrCode WebviewController::CloseCamera()
1556 {
1557     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1558     if (!nweb_ptr) {
1559         return NWebError::INIT_ERROR;
1560     }
1561 
1562     nweb_ptr->CloseCamera();
1563     return NWebError::NO_ERROR;
1564 }
1565 
GetLastJavascriptProxyCallingFrameUrl()1566 std::string WebviewController::GetLastJavascriptProxyCallingFrameUrl()
1567 {
1568     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1569     if (!nweb_ptr) {
1570         return "";
1571     }
1572 
1573     return nweb_ptr->GetLastJavascriptProxyCallingFrameUrl();
1574 }
1575 
OnCreateNativeMediaPlayer(napi_env env, napi_ref callback)1576 void WebviewController::OnCreateNativeMediaPlayer(napi_env env, napi_ref callback)
1577 {
1578     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1579     if (!nweb_ptr) {
1580         return;
1581     }
1582 
1583     auto callbackImpl = std::make_shared<NWebCreateNativeMediaPlayerCallbackImpl>(nwebId_, env, callback);
1584     nweb_ptr->OnCreateNativeMediaPlayer(callbackImpl);
1585 }
1586 
ParseScriptContent(napi_env env, napi_value value, std::string &script)1587 bool WebviewController::ParseScriptContent(napi_env env, napi_value value, std::string &script)
1588 {
1589     napi_valuetype valueType;
1590     napi_typeof(env, value, &valueType);
1591     if (valueType == napi_string) {
1592         std::string str;
1593         if (!NapiParseUtils::ParseString(env, value, str)) {
1594             WVLOG_E("PrecompileJavaScript: parse script text to string failed.");
1595             return false;
1596         }
1597 
1598         script = str;
1599         return true;
1600     }
1601 
1602     std::vector<uint8_t> vec = ParseUint8Array(env, value);
1603     if (!vec.size()) {
1604         WVLOG_E("PrecompileJavaScript: parse script text to Uint8Array failed.");
1605         return false;
1606     }
1607 
1608     std::string str(vec.begin(), vec.end());
1609     script = str;
1610     return true;
1611 }
1612 
ParseCacheOptions(napi_env env, napi_value value)1613 std::shared_ptr<CacheOptions> WebviewController::ParseCacheOptions(napi_env env, napi_value value) {
1614     std::map<std::string, std::string> responseHeaders;
1615     auto defaultCacheOptions = std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1616 
1617     napi_value responseHeadersValue = nullptr;
1618     if (napi_get_named_property(env, value, "responseHeaders", &responseHeadersValue) != napi_ok) {
1619         WVLOG_D("PrecompileJavaScript: cannot get 'responseHeaders' of CacheOptions.");
1620         return defaultCacheOptions;
1621     }
1622 
1623     if (!ParseResponseHeaders(env, responseHeadersValue, responseHeaders)) {
1624         WVLOG_D("PrecompileJavaScript: parse 'responseHeaders' of CacheOptions failed. use default options");
1625         return defaultCacheOptions;
1626     }
1627 
1628     return std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1629 }
1630 
PrecompileJavaScriptPromise( napi_env env, napi_deferred deferred, const std::string &url, const std::string &script, std::shared_ptr<CacheOptions> cacheOptions)1631 void WebviewController::PrecompileJavaScriptPromise(
1632     napi_env env, napi_deferred deferred,
1633     const std::string &url, const std::string &script, std::shared_ptr<CacheOptions> cacheOptions)
1634 {
1635     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1636     if (!nweb_ptr || !deferred) {
1637         return;
1638     }
1639 
1640     auto callbackImpl = std::make_shared<OHOS::NWeb::NWebPrecompileCallback>();
1641     callbackImpl->SetCallback([env, deferred](int64_t result) {
1642         if (!env) {
1643             return;
1644         }
1645 
1646         napi_handle_scope scope = nullptr;
1647         napi_open_handle_scope(env, &scope);
1648         if (scope == nullptr) {
1649             return;
1650         }
1651 
1652         napi_value setResult[RESULT_COUNT] = {0};
1653         napi_create_int64(env, result, &setResult[PARAMZERO]);
1654         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO]};
1655         if (result == static_cast<int64_t>(PrecompileError::OK)) {
1656             napi_resolve_deferred(env, deferred, args[PARAMZERO]);
1657         } else {
1658             napi_reject_deferred(env, deferred, args[PARAMZERO]);
1659         }
1660 
1661         napi_close_handle_scope(env, scope);
1662     });
1663 
1664     nweb_ptr->PrecompileJavaScript(url, script, cacheOptions, callbackImpl);
1665 }
1666 
ParseResponseHeaders(napi_env env, napi_value value, std::map<std::string, std::string> &responseHeaders) const1667 bool WebviewController::ParseResponseHeaders(napi_env env,
1668                                              napi_value value,
1669                                              std::map<std::string, std::string> &responseHeaders) const
1670 {
1671     bool isArray = false;
1672     napi_is_array(env, value, &isArray);
1673     if (!isArray) {
1674         WVLOG_E("Response headers is not array.");
1675         return false;
1676     }
1677 
1678     uint32_t length = INTEGER_ZERO;
1679     napi_get_array_length(env, value, &length);
1680     for (uint32_t i = 0; i < length; i++) {
1681         std::string keyString;
1682         std::string valueString;
1683         napi_value header = nullptr;
1684         napi_value keyObj = nullptr;
1685         napi_value valueObj = nullptr;
1686         napi_get_element(env, value, i, &header);
1687 
1688         if (napi_get_named_property(env, header, "headerKey", &keyObj) != napi_ok ||
1689             !NapiParseUtils::ParseString(env, keyObj, keyString)) {
1690             continue;
1691         }
1692 
1693         if (napi_get_named_property(env, header, "headerValue", &valueObj) != napi_ok ||
1694             !NapiParseUtils::ParseString(env, valueObj, valueString)) {
1695             continue;
1696         }
1697 
1698         responseHeaders[keyString] = valueString;
1699     }
1700 
1701     return true;
1702 }
1703 
ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList)1704 ParseURLResult WebviewController::ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList)
1705 {
1706     if (!NapiParseUtils::ParseStringArray(env, value, urlList)) {
1707         return ParseURLResult::FAILED;
1708     }
1709 
1710     for (auto url : urlList) {
1711         if (!CheckURL(url)) {
1712             return ParseURLResult::INVALID_URL;
1713         }
1714     }
1715 
1716     return ParseURLResult::OK;
1717 }
1718 
CheckURL(std::string& url) const1719 bool WebviewController::CheckURL(std::string& url) const
1720 {
1721     if (url.size() > URL_MAXIMUM) {
1722         WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{private}s", URL_MAXIMUM, url.c_str());
1723         return false;
1724     }
1725 
1726     if (!regex_match(url, std::regex("^http(s)?:\\/\\/.+", std::regex_constants::icase))) {
1727         WVLOG_E("The Parse URL error. URL: %{private}s", url.c_str());
1728         return false;
1729     }
1730 
1731     return true;
1732 }
1733 
ParseUint8Array(napi_env env, napi_value value)1734 std::vector<uint8_t> WebviewController::ParseUint8Array(napi_env env, napi_value value)
1735 {
1736     napi_typedarray_type typedArrayType;
1737     size_t length = 0;
1738     napi_value buffer = nullptr;
1739     size_t offset = 0;
1740     napi_get_typedarray_info(env, value, &typedArrayType, &length, nullptr, &buffer, &offset);
1741     if (typedArrayType != napi_uint8_array) {
1742         WVLOG_E("Param is not Unit8Array.");
1743         return std::vector<uint8_t>();
1744     }
1745 
1746     uint8_t *data = nullptr;
1747     size_t total = 0;
1748     napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total);
1749     length = std::min<size_t>(length, total - offset);
1750     std::vector<uint8_t> vec(length);
1751     int retCode = memcpy_s(vec.data(), vec.size(), &data[offset], length);
1752     if (retCode != 0) {
1753         WVLOG_E("Parse Uint8Array failed.");
1754         return std::vector<uint8_t>();
1755     }
1756 
1757     return vec;
1758 }
1759 
InjectOfflineResource(const std::vector<std::string>& urlList, const std::vector<uint8_t>& resource, const std::map<std::string, std::string>& response_headers, const uint32_t type)1760 void WebviewController::InjectOfflineResource(const std::vector<std::string>& urlList,
1761                                               const std::vector<uint8_t>& resource,
1762                                               const std::map<std::string, std::string>& response_headers,
1763                                               const uint32_t type)
1764 {
1765     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1766     if (!nweb_ptr) {
1767         return;
1768     }
1769 
1770     std::string originUrl = urlList[0];
1771     if (urlList.size() == 1) {
1772         nweb_ptr->InjectOfflineResource(originUrl, originUrl, resource, response_headers, type);
1773         return;
1774     }
1775 
1776     for (size_t i = 1 ; i < urlList.size() ; i++) {
1777         nweb_ptr->InjectOfflineResource(urlList[i], originUrl, resource, response_headers, type);
1778     }
1779 }
1780 
EnableAdsBlock(bool enable)1781 void WebviewController::EnableAdsBlock(bool enable)
1782 {
1783     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1784     if (nweb_ptr) {
1785         nweb_ptr->EnableAdsBlock(enable);
1786     }
1787 }
1788 
IsAdsBlockEnabled() const1789 bool WebviewController::IsAdsBlockEnabled() const
1790 {
1791     bool enabled = false;
1792     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1793     if (nweb_ptr) {
1794         enabled = nweb_ptr->IsAdsBlockEnabled();
1795     }
1796     return enabled;
1797 }
1798 
IsAdsBlockEnabledForCurPage() const1799 bool WebviewController::IsAdsBlockEnabledForCurPage() const
1800 {
1801     bool enabled = false;
1802     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1803     if (nweb_ptr) {
1804         enabled = nweb_ptr->IsAdsBlockEnabledForCurPage();
1805     }
1806     return enabled;
1807 }
1808 
GetSurfaceId()1809 std::string WebviewController::GetSurfaceId()
1810 {
1811     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1812     if (!nweb_ptr) {
1813         return "";
1814     }
1815     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1816     if (!setting) {
1817         return "";
1818     }
1819     return setting->GetSurfaceId();
1820 }
1821 
UpdateInstanceId(int32_t newId)1822 void WebviewController::UpdateInstanceId(int32_t newId)
1823 {
1824     if (javaScriptResultCb_) {
1825         javaScriptResultCb_->UpdateInstanceId(newId);
1826     }
1827 }
1828 
SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg)1829 ErrCode WebviewController::SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg)
1830 {
1831     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1832     if (!nweb_ptr) {
1833         return NWebError::INIT_ERROR;
1834     }
1835 
1836     int ret = NWebError::NO_ERROR;
1837     switch (nweb_ptr->SetUrlTrustListWithErrMsg(urlTrustList, detailErrMsg)) {
1838         case static_cast<int>(UrlListSetResult::INIT_ERROR):
1839             ret = NWebError::INIT_ERROR;
1840             break;
1841         case static_cast<int>(UrlListSetResult::PARAM_ERROR):
1842             ret = NWebError::PARAM_CHECK_ERROR;
1843             break;
1844         case static_cast<int>(UrlListSetResult::SET_OK):
1845             ret = NWebError::NO_ERROR;
1846             break;
1847         default:
1848             ret = NWebError::PARAM_CHECK_ERROR;
1849             break;
1850     }
1851     return ret;
1852 }
ParseJsLengthResourceToInt( napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const1853 bool WebviewController::ParseJsLengthResourceToInt(
1854     napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const
1855 {
1856     napi_value resIdObj = nullptr;
1857     int32_t resId;
1858 
1859     if ((napi_get_named_property(env, jsLength, "id", &resIdObj) != napi_ok)) {
1860         return false;
1861     }
1862 
1863     if (!NapiParseUtils::ParseInt32(env, resIdObj, resId)) {
1864         return false;
1865     }
1866 
1867     std::shared_ptr<AbilityRuntime::ApplicationContext> context =
1868         AbilityRuntime::ApplicationContext::GetApplicationContext();
1869     if (!context) {
1870         WVLOG_E("WebPageSnapshot Failed to get application context.");
1871         return false;
1872     }
1873     auto resourceManager = context->GetResourceManager();
1874     if (!resourceManager) {
1875         WVLOG_E("WebPageSnapshot Failed to get resource manager.");
1876         return false;
1877     }
1878 
1879     napi_value jsResourceType = nullptr;
1880     napi_valuetype resourceType = napi_null;
1881     napi_get_named_property(env, jsLength, "type", &jsResourceType);
1882     napi_typeof(env, jsResourceType, &resourceType);
1883     if (resourceType == napi_number) {
1884         int32_t resourceTypeNum;
1885         NapiParseUtils::ParseInt32(env, jsResourceType, resourceTypeNum);
1886         switch (resourceTypeNum) {
1887             case static_cast<int>(ResourceType::INTEGER):
1888                 if (resourceManager->GetIntegerById(resId, result) == Global::Resource::SUCCESS) {
1889                     type = PixelUnit::VP;
1890                     return true;
1891                 }
1892                 break;
1893             case static_cast<int>(ResourceType::STRING):
1894                 std::string resourceString;
1895                 if (resourceManager->GetStringById(resId, resourceString) == Global::Resource::SUCCESS) {
1896                     return NapiParseUtils::ParseJsLengthStringToInt(resourceString, type, result);
1897                 }
1898                 break;
1899         }
1900         WVLOG_E("WebPageSnapshot resource type not support");
1901         return false;
1902     }
1903     WVLOG_E("WebPageSnapshot resource type error");
1904     return false;
1905 }
1906 
ParseJsLengthToInt( napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const1907 bool WebviewController::ParseJsLengthToInt(
1908     napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const
1909 {
1910     napi_valuetype jsType = napi_null;
1911     napi_typeof(env, jsLength, &jsType);
1912     if ((jsType != napi_object) && (jsType != napi_string) && (jsType != napi_number)) {
1913         WVLOG_E("WebPageSnapshot Unable to parse js length object.");
1914         return false;
1915     }
1916 
1917     if (jsType == napi_number) {
1918         NapiParseUtils::ParseInt32(env, jsLength, result);
1919         type = PixelUnit::VP;
1920         return true;
1921     }
1922 
1923     if (jsType == napi_string) {
1924         std::string nativeString;
1925         NapiParseUtils::ParseString(env, jsLength, nativeString);
1926         if (!NapiParseUtils::ParseJsLengthStringToInt(nativeString, type, result)) {
1927             return false;
1928         }
1929         return true;
1930     }
1931 
1932     if (jsType == napi_object) {
1933         return ParseJsLengthResourceToInt(env, jsLength, type, result);
1934     }
1935     return false;
1936 }
1937 
WebPageSnapshot( const char *id, PixelUnit type, int32_t width, int32_t height, const WebSnapshotCallback callback)1938 ErrCode WebviewController::WebPageSnapshot(
1939     const char *id, PixelUnit type, int32_t width, int32_t height, const WebSnapshotCallback callback)
1940 {
1941     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1942     if (!nweb_ptr) {
1943         return INIT_ERROR;
1944     }
1945 
1946     bool init = nweb_ptr->WebPageSnapshot(id, type, width, height, std::move(callback));
1947     if (!init) {
1948         return INIT_ERROR;
1949     }
1950 
1951     return NWebError::NO_ERROR;
1952 }
1953 
GetHapModuleInfo()1954 bool WebviewController::GetHapModuleInfo()
1955 {
1956     sptr<ISystemAbilityManager> systemAbilityManager =
1957     SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1958     if (systemAbilityManager == nullptr) {
1959         WVLOG_E("get SystemAbilityManager failed");
1960         return false;
1961     }
1962     sptr<IRemoteObject> remoteObject =
1963         systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1964     if (remoteObject == nullptr) {
1965         WVLOG_E("get Bundle Manager failed");
1966         return false;
1967     }
1968     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1969     if (bundleMgr == nullptr) {
1970         WVLOG_E("get Bundle Manager failed");
1971         return false;
1972     }
1973     AppExecFwk::BundleInfo bundleInfo;
1974     if (bundleMgr->GetBundleInfoForSelf(
1975         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
1976         bundleInfo) != 0) {
1977         WVLOG_E("get bundle info failed");
1978         return false;
1979     }
1980     moduleName_ = bundleInfo.moduleNames;
1981     return true;
1982 }
1983 
SetPathAllowingUniversalAccess( const std::vector<std::string>& pathList, std::string& errorPath)1984 void WebviewController::SetPathAllowingUniversalAccess(
1985     const std::vector<std::string>& pathList, std::string& errorPath)
1986 {
1987     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1988     if (!nweb_ptr) {
1989         return;
1990     }
1991     if (moduleName_.empty()) {
1992         WVLOG_I("need to get module name for path");
1993         if (!GetHapModuleInfo()) {
1994             WVLOG_E("GetHapModuleInfo failed");
1995             moduleName_.clear();
1996             return;
1997         }
1998     }
1999     nweb_ptr->SetPathAllowingUniversalAccess(pathList, moduleName_, errorPath);
2000 }
2001 
ScrollToWithAnime(float x, float y, int32_t duration)2002 void WebviewController::ScrollToWithAnime(float x, float y, int32_t duration)
2003 {
2004     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2005     if (nweb_ptr) {
2006         nweb_ptr->ScrollToWithAnime(x, y, duration);
2007     }
2008     return;
2009 }
2010 
ScrollByWithAnime(float deltaX, float deltaY, int32_t duration)2011 void WebviewController::ScrollByWithAnime(float deltaX, float deltaY, int32_t duration)
2012 {
2013     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2014     if (nweb_ptr) {
2015         nweb_ptr->ScrollByWithAnime(deltaX, deltaY, duration);
2016     }
2017     return;
2018 }
2019 
SetBackForwardCacheOptions(int32_t size, int32_t timeToLive)2020 void WebviewController::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive)
2021 {
2022     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2023     if (!nweb_ptr) {
2024         return;
2025     }
2026 
2027     nweb_ptr->SetBackForwardCacheOptions(size, timeToLive);
2028 }
2029 
GetScrollOffset(float* offset_x, float* offset_y)2030 void WebviewController::GetScrollOffset(float* offset_x, float* offset_y)
2031 {
2032     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2033     if (nweb_ptr) {
2034         nweb_ptr->GetScrollOffset(offset_x, offset_y);
2035     }
2036 }
2037 
ScrollByWithResult(float deltaX, float deltaY) const2038 bool WebviewController::ScrollByWithResult(float deltaX, float deltaY) const
2039 {
2040     bool enabled = false;
2041     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2042     if (nweb_ptr) {
2043         enabled = nweb_ptr->ScrollByWithResult(deltaX, deltaY);
2044     }
2045     return enabled;
2046 }
2047 
SetScrollable(bool enable, int32_t scrollType)2048 void WebviewController::SetScrollable(bool enable, int32_t scrollType)
2049 {
2050     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2051     if (!nweb_ptr) {
2052         return;
2053     }
2054     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
2055     if (!setting) {
2056         return;
2057     }
2058     return setting->SetScrollable(enable, scrollType);
2059 }
2060 
SetType(int type)2061 void WebMessageExt::SetType(int type)
2062 {
2063     type_ = type;
2064     WebMessageType jsType = static_cast<WebMessageType>(type);
2065     NWebValue::Type nwebType = NWebValue::Type::NONE;
2066     switch (jsType) {
2067         case WebMessageType::STRING: {
2068             nwebType = NWebValue::Type::STRING;
2069             break;
2070         }
2071         case WebMessageType::NUMBER: {
2072             nwebType = NWebValue::Type::DOUBLE;
2073             break;
2074         }
2075         case WebMessageType::BOOLEAN: {
2076             nwebType = NWebValue::Type::BOOLEAN;
2077             break;
2078         }
2079         case WebMessageType::ARRAYBUFFER: {
2080             nwebType = NWebValue::Type::BINARY;
2081             break;
2082         }
2083         case WebMessageType::ARRAY: {
2084             nwebType = NWebValue::Type::STRINGARRAY;
2085             break;
2086         }
2087         case WebMessageType::ERROR: {
2088             nwebType = NWebValue::Type::ERROR;
2089             break;
2090         }
2091         default: {
2092             nwebType = NWebValue::Type::NONE;
2093             break;
2094         }
2095     }
2096     if (data_) {
2097         data_->SetType(nwebType);
2098     }
2099 }
2100 
ConvertNwebType2JsType(NWebValue::Type type)2101 int WebMessageExt::ConvertNwebType2JsType(NWebValue::Type type)
2102 {
2103     WebMessageType jsType = WebMessageType::NOTSUPPORT;
2104     switch (type) {
2105         case NWebValue::Type::STRING: {
2106             jsType = WebMessageType::STRING;
2107             break;
2108         }
2109         case NWebValue::Type::DOUBLE:
2110         case NWebValue::Type::INTEGER: {
2111             jsType = WebMessageType::NUMBER;
2112             break;
2113         }
2114         case NWebValue::Type::BOOLEAN: {
2115             jsType = WebMessageType::BOOLEAN;
2116             break;
2117         }
2118         case NWebValue::Type::STRINGARRAY:
2119         case NWebValue::Type::DOUBLEARRAY:
2120         case NWebValue::Type::INT64ARRAY:
2121         case NWebValue::Type::BOOLEANARRAY: {
2122             jsType = WebMessageType::ARRAY;
2123             break;
2124         }
2125         case NWebValue::Type::BINARY: {
2126             jsType = WebMessageType::ARRAYBUFFER;
2127             break;
2128         }
2129         case NWebValue::Type::ERROR: {
2130             jsType = WebMessageType::ERROR;
2131             break;
2132         }
2133         default: {
2134             jsType = WebMessageType::NOTSUPPORT;
2135             break;
2136         }
2137     }
2138     return static_cast<int>(jsType);
2139 }
2140 
2141 } // namespace NWeb
2142 } // namespace OHOS
2143