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()202 bool WebviewController::IsInit()
203 {
204     return NWebHelper::Instance().GetNWeb(nwebId_) ? true : false;
205 }
206 
AccessForward()207 bool WebviewController::AccessForward()
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()219 bool WebviewController::AccessBackward()
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)229 bool WebviewController::AccessStep(int32_t step)
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)592 bool WebviewController::GetRawFileUrl(const std::string &fileName,
593     const std::string& bundleName, const std::string& moduleName, std::string &result)
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)625 bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result)
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)661 bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result)
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)686 bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result)
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()834 bool WebviewController::IsSafeBrowsingEnabled()
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 tmp;
949     tmp.env = param.env;
950     tmp.obj = param.obj;
951     tmp.objName = param.objName;
952     tmp.syncMethodList = allMethodList;
953     tmp.asyncMethodList = param.asyncMethodList;
954     tmp.permission = param.permission;
955     objId = javaScriptResultCb_->RegisterJavaScriptProxy(tmp);
956 
957     nweb_ptr->RegisterArkJSfunctionV2(tmp.objName, tmp.syncMethodList,
958                                       tmp.asyncMethodList, objId, 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()1116 bool WebviewController::TerminateRenderProcess()
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)1215 bool WebviewController::GetFavicon(
1216     const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType)
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)1236 bool WebviewController::RestoreWebState(const std::vector<uint8_t> &state)
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()1304 bool WebviewController::GetScrollable()
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)1322 bool WebviewController::GetCertChainDerData(std::vector<std::string> &certChainDerData)
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()1452 bool WebviewController::IsIncognitoMode()
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()1470 bool  WebviewController::GetPrintBackground()
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()1489 bool WebviewController::IsIntelligentTrackingPreventionEnabled()
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)1504 bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler)
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 
GetLastJavascriptProxyCallingFrameUrl()1533 std::string WebviewController::GetLastJavascriptProxyCallingFrameUrl()
1534 {
1535     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1536     if (!nweb_ptr) {
1537         return "";
1538     }
1539 
1540     return nweb_ptr->GetLastJavascriptProxyCallingFrameUrl();
1541 }
1542 
StartCamera()1543 ErrCode WebviewController::StartCamera()
1544 {
1545     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1546     if (!nweb_ptr) {
1547         return NWebError::INIT_ERROR;
1548     }
1549 
1550     nweb_ptr->StartCamera();
1551     return NWebError::NO_ERROR;
1552 }
1553 
StopCamera()1554 ErrCode WebviewController::StopCamera()
1555 {
1556     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1557     if (!nweb_ptr) {
1558         return NWebError::INIT_ERROR;
1559     }
1560 
1561     nweb_ptr->StopCamera();
1562     return NWebError::NO_ERROR;
1563 }
1564 
CloseCamera()1565 ErrCode WebviewController::CloseCamera()
1566 {
1567     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1568     if (!nweb_ptr) {
1569         return NWebError::INIT_ERROR;
1570     }
1571 
1572     nweb_ptr->CloseCamera();
1573     return NWebError::NO_ERROR;
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 {
1615     std::map<std::string, std::string> responseHeaders;
1616     auto defaultCacheOptions = std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1617 
1618     napi_value responseHeadersValue = nullptr;
1619     if (napi_get_named_property(env, value, "responseHeaders", &responseHeadersValue) != napi_ok) {
1620         WVLOG_D("PrecompileJavaScript: cannot get 'responseHeaders' of CacheOptions.");
1621         return defaultCacheOptions;
1622     }
1623 
1624     if (!ParseResponseHeaders(env, responseHeadersValue, responseHeaders)) {
1625         WVLOG_D("PrecompileJavaScript: parse 'responseHeaders' of CacheOptions failed. use default options");
1626         return defaultCacheOptions;
1627     }
1628 
1629     return std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1630 }
1631 
PrecompileJavaScriptPromise(napi_env env,napi_deferred deferred,const std::string & url,const std::string & script,std::shared_ptr<CacheOptions> cacheOptions)1632 void WebviewController::PrecompileJavaScriptPromise(
1633     napi_env env, napi_deferred deferred,
1634     const std::string &url, const std::string &script, std::shared_ptr<CacheOptions> cacheOptions)
1635 {
1636     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1637     if (!nweb_ptr || !deferred) {
1638         return;
1639     }
1640 
1641     auto callbackImpl = std::make_shared<OHOS::NWeb::NWebPrecompileCallback>();
1642     callbackImpl->SetCallback([env, deferred](int64_t result) {
1643         if (!env) {
1644             return;
1645         }
1646 
1647         napi_handle_scope scope = nullptr;
1648         napi_open_handle_scope(env, &scope);
1649         if (scope == nullptr) {
1650             return;
1651         }
1652 
1653         napi_value setResult[RESULT_COUNT] = {0};
1654         napi_create_int64(env, result, &setResult[PARAMZERO]);
1655         napi_value args[RESULT_COUNT] = {setResult[PARAMZERO]};
1656         if (result == static_cast<int64_t>(PrecompileError::OK)) {
1657             napi_resolve_deferred(env, deferred, args[PARAMZERO]);
1658         } else {
1659             napi_reject_deferred(env, deferred, args[PARAMZERO]);
1660         }
1661 
1662         napi_close_handle_scope(env, scope);
1663     });
1664 
1665     nweb_ptr->PrecompileJavaScript(url, script, cacheOptions, callbackImpl);
1666 }
1667 
ParseResponseHeaders(napi_env env,napi_value value,std::map<std::string,std::string> & responseHeaders)1668 bool WebviewController::ParseResponseHeaders(napi_env env,
1669                                              napi_value value,
1670                                              std::map<std::string, std::string> &responseHeaders)
1671 {
1672     bool isArray = false;
1673     napi_is_array(env, value, &isArray);
1674     if (!isArray) {
1675         WVLOG_E("Response headers is not array.");
1676         return false;
1677     }
1678 
1679     uint32_t length = INTEGER_ZERO;
1680     napi_get_array_length(env, value, &length);
1681     for (uint32_t i = 0; i < length; i++) {
1682         std::string keyString;
1683         std::string valueString;
1684         napi_value header = nullptr;
1685         napi_value keyObj = nullptr;
1686         napi_value valueObj = nullptr;
1687         napi_get_element(env, value, i, &header);
1688 
1689         if (napi_get_named_property(env, header, "headerKey", &keyObj) != napi_ok ||
1690             !NapiParseUtils::ParseString(env, keyObj, keyString)) {
1691             continue;
1692         }
1693 
1694         if (napi_get_named_property(env, header, "headerValue", &valueObj) != napi_ok ||
1695             !NapiParseUtils::ParseString(env, valueObj, valueString)) {
1696             continue;
1697         }
1698 
1699         responseHeaders[keyString] = valueString;
1700     }
1701 
1702     return true;
1703 }
1704 
ParseURLList(napi_env env,napi_value value,std::vector<std::string> & urlList)1705 ParseURLResult WebviewController::ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList)
1706 {
1707     if (!NapiParseUtils::ParseStringArray(env, value, urlList)) {
1708         return ParseURLResult::FAILED;
1709     }
1710 
1711     for (auto url : urlList) {
1712         if (!CheckURL(url)) {
1713             return ParseURLResult::INVALID_URL;
1714         }
1715     }
1716 
1717     return ParseURLResult::OK;
1718 }
1719 
CheckURL(std::string & url)1720 bool WebviewController::CheckURL(std::string& url)
1721 {
1722     if (url.size() > URL_MAXIMUM) {
1723         WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{private}s", URL_MAXIMUM, url.c_str());
1724         return false;
1725     }
1726 
1727     if (!regex_match(url, std::regex("^http(s)?:\\/\\/.+", std::regex_constants::icase))) {
1728         WVLOG_E("The Parse URL error. URL: %{private}s", url.c_str());
1729         return false;
1730     }
1731 
1732     return true;
1733 }
1734 
ParseUint8Array(napi_env env,napi_value value)1735 std::vector<uint8_t> WebviewController::ParseUint8Array(napi_env env, napi_value value)
1736 {
1737     napi_typedarray_type typedArrayType;
1738     size_t length = 0;
1739     napi_value buffer = nullptr;
1740     size_t offset = 0;
1741     napi_get_typedarray_info(env, value, &typedArrayType, &length, nullptr, &buffer, &offset);
1742     if (typedArrayType != napi_uint8_array) {
1743         WVLOG_E("Param is not Unit8Array.");
1744         return std::vector<uint8_t>();
1745     }
1746 
1747     uint8_t *data = nullptr;
1748     size_t total = 0;
1749     napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total);
1750     length = std::min<size_t>(length, total - offset);
1751     std::vector<uint8_t> vec(length);
1752     int retCode = memcpy_s(vec.data(), vec.size(), &data[offset], length);
1753     if (retCode != 0) {
1754         WVLOG_E("Parse Uint8Array failed.");
1755         return std::vector<uint8_t>();
1756     }
1757 
1758     return vec;
1759 }
1760 
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)1761 void WebviewController::InjectOfflineResource(const std::vector<std::string>& urlList,
1762                                               const std::vector<uint8_t>& resource,
1763                                               const std::map<std::string, std::string>& response_headers,
1764                                               const uint32_t type)
1765 {
1766     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1767     if (!nweb_ptr) {
1768         return;
1769     }
1770 
1771     std::string originUrl = urlList[0];
1772     if (urlList.size() == 1) {
1773         nweb_ptr->InjectOfflineResource(originUrl, originUrl, resource, response_headers, type);
1774         return;
1775     }
1776 
1777     for (size_t i = 1 ; i < urlList.size() ; i++) {
1778         nweb_ptr->InjectOfflineResource(urlList[i], originUrl, resource, response_headers, type);
1779     }
1780 }
1781 
GetSurfaceId()1782 std::string WebviewController::GetSurfaceId()
1783 {
1784     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1785     if (!nweb_ptr) {
1786         return "";
1787     }
1788     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1789     if (!setting) {
1790         return "";
1791     }
1792     return setting->GetSurfaceId();
1793 }
1794 
EnableAdsBlock(bool enable)1795 void WebviewController::EnableAdsBlock(bool enable)
1796 {
1797     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1798     if (nweb_ptr) {
1799         nweb_ptr->EnableAdsBlock(enable);
1800     }
1801 }
1802 
IsAdsBlockEnabled()1803 bool WebviewController::IsAdsBlockEnabled()
1804 {
1805     bool enabled = false;
1806     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1807     if (nweb_ptr) {
1808         enabled = nweb_ptr->IsAdsBlockEnabled();
1809     }
1810     return enabled;
1811 }
1812 
IsAdsBlockEnabledForCurPage()1813 bool WebviewController::IsAdsBlockEnabledForCurPage()
1814 {
1815     bool enabled = false;
1816     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1817     if (nweb_ptr) {
1818         enabled = nweb_ptr->IsAdsBlockEnabledForCurPage();
1819     }
1820     return enabled;
1821 }
1822 
ParseJsLengthResourceToInt(napi_env env,napi_value jsLength,PixelUnit & type,int32_t & result)1823 bool WebviewController::ParseJsLengthResourceToInt(
1824     napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result)
1825 {
1826     napi_value resIdObj = nullptr;
1827     int32_t resId;
1828 
1829     if ((napi_get_named_property(env, jsLength, "id", &resIdObj) != napi_ok)) {
1830         return false;
1831     }
1832 
1833     if (!NapiParseUtils::ParseInt32(env, resIdObj, resId)) {
1834         return false;
1835     }
1836 
1837     std::shared_ptr<AbilityRuntime::ApplicationContext> context =
1838         AbilityRuntime::ApplicationContext::GetApplicationContext();
1839     if (!context) {
1840         WVLOG_E("WebPageSnapshot Failed to get application context.");
1841         return false;
1842     }
1843     auto resourceManager = context->GetResourceManager();
1844     if (!resourceManager) {
1845         WVLOG_E("WebPageSnapshot Failed to get resource manager.");
1846         return false;
1847     }
1848 
1849     napi_value jsResourceType = nullptr;
1850     napi_valuetype resourceType = napi_null;
1851     napi_get_named_property(env, jsLength, "type", &jsResourceType);
1852     napi_typeof(env, jsResourceType, &resourceType);
1853     if (resourceType == napi_number) {
1854         int32_t resourceTypeNum;
1855         NapiParseUtils::ParseInt32(env, jsResourceType, resourceTypeNum);
1856         std::string resourceString;
1857         switch (resourceTypeNum) {
1858             case static_cast<int>(ResourceType::INTEGER):
1859                 if (resourceManager->GetIntegerById(resId, result) == Global::Resource::SUCCESS) {
1860                     type = PixelUnit::VP;
1861                     return true;
1862                 }
1863                 break;
1864             case static_cast<int>(ResourceType::STRING):
1865                 if (resourceManager->GetStringById(resId, resourceString) == Global::Resource::SUCCESS) {
1866                     return NapiParseUtils::ParseJsLengthStringToInt(resourceString, type, result);
1867                 }
1868                 break;
1869             default:
1870                 WVLOG_E("WebPageSnapshot resource type not support");
1871                 break;
1872         }
1873         return false;
1874     }
1875     WVLOG_E("WebPageSnapshot resource type error");
1876     return false;
1877 }
1878 
ParseJsLengthToInt(napi_env env,napi_value jsLength,PixelUnit & type,int32_t & result)1879 bool WebviewController::ParseJsLengthToInt(
1880     napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result)
1881 {
1882     napi_valuetype jsType = napi_null;
1883     napi_typeof(env, jsLength, &jsType);
1884     if ((jsType != napi_object) && (jsType != napi_string) && (jsType != napi_number)) {
1885         WVLOG_E("WebPageSnapshot Unable to parse js length object.");
1886         return false;
1887     }
1888 
1889     if (jsType == napi_number) {
1890         NapiParseUtils::ParseInt32(env, jsLength, result);
1891         type = PixelUnit::VP;
1892         return true;
1893     }
1894 
1895     if (jsType == napi_string) {
1896         std::string nativeString;
1897         NapiParseUtils::ParseString(env, jsLength, nativeString);
1898         if (!NapiParseUtils::ParseJsLengthStringToInt(nativeString, type, result)) {
1899             return false;
1900         }
1901         return true;
1902     }
1903 
1904     if (jsType == napi_object) {
1905         return ParseJsLengthResourceToInt(env, jsLength, type, result);
1906     }
1907     return false;
1908 }
1909 
WebPageSnapshot(const char * id,PixelUnit type,int32_t width,int32_t height,const WebSnapshotCallback callback)1910 ErrCode WebviewController::WebPageSnapshot(
1911     const char *id, PixelUnit type, int32_t width, int32_t height, const WebSnapshotCallback callback)
1912 {
1913     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1914     if (!nweb_ptr) {
1915         return INIT_ERROR;
1916     }
1917 
1918     bool init = nweb_ptr->WebPageSnapshot(id, type, width, height, std::move(callback));
1919     if (!init) {
1920         return INIT_ERROR;
1921     }
1922 
1923     return NWebError::NO_ERROR;
1924 }
1925 
SetUrlTrustList(const std::string & urlTrustList,std::string & detailErrMsg)1926 ErrCode WebviewController::SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg)
1927 {
1928     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1929     if (!nweb_ptr) {
1930         return NWebError::INIT_ERROR;
1931     }
1932 
1933     int ret = NWebError::NO_ERROR;
1934     switch (nweb_ptr->SetUrlTrustListWithErrMsg(urlTrustList, detailErrMsg)) {
1935         case static_cast<int>(UrlListSetResult::INIT_ERROR):
1936             ret = NWebError::INIT_ERROR;
1937             break;
1938         case static_cast<int>(UrlListSetResult::PARAM_ERROR):
1939             ret = NWebError::PARAM_CHECK_ERROR;
1940             break;
1941         case static_cast<int>(UrlListSetResult::SET_OK):
1942             ret = NWebError::NO_ERROR;
1943             break;
1944         default:
1945             ret = NWebError::PARAM_CHECK_ERROR;
1946             break;
1947     }
1948     return ret;
1949 }
1950 
UpdateInstanceId(int32_t newId)1951 void WebviewController::UpdateInstanceId(int32_t newId)
1952 {
1953     if (javaScriptResultCb_) {
1954         javaScriptResultCb_->UpdateInstanceId(newId);
1955     }
1956 }
1957 
SetBackForwardCacheOptions(int32_t size,int32_t timeToLive)1958 void WebviewController::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive)
1959 {
1960     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1961     if (!nweb_ptr) {
1962         return;
1963     }
1964 
1965     nweb_ptr->SetBackForwardCacheOptions(size, timeToLive);
1966 }
1967 
GetHapModuleInfo()1968 bool WebviewController::GetHapModuleInfo()
1969 {
1970     sptr<ISystemAbilityManager> systemAbilityManager =
1971     SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1972     if (systemAbilityManager == nullptr) {
1973         WVLOG_E("get SystemAbilityManager failed");
1974         return false;
1975     }
1976     sptr<IRemoteObject> remoteObject =
1977         systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1978     if (remoteObject == nullptr) {
1979         WVLOG_E("get Bundle Manager failed");
1980         return false;
1981     }
1982     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1983     if (bundleMgr == nullptr) {
1984         WVLOG_E("get Bundle Manager failed");
1985         return false;
1986     }
1987     AppExecFwk::BundleInfo bundleInfo;
1988     if (bundleMgr->GetBundleInfoForSelf(
1989         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
1990         bundleInfo) != 0) {
1991         WVLOG_E("get bundle info failed");
1992         return false;
1993     }
1994     moduleName_ = bundleInfo.moduleNames;
1995     return true;
1996 }
1997 
SetPathAllowingUniversalAccess(const std::vector<std::string> & pathList,std::string & errorPath)1998 void WebviewController::SetPathAllowingUniversalAccess(
1999     const std::vector<std::string>& pathList, std::string& errorPath)
2000 {
2001     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2002     if (!nweb_ptr) {
2003         return;
2004     }
2005     if (moduleName_.empty()) {
2006         WVLOG_I("need to get module name for path");
2007         if (!GetHapModuleInfo()) {
2008             WVLOG_E("GetHapModuleInfo failed");
2009             moduleName_.clear();
2010             return;
2011         }
2012     }
2013     nweb_ptr->SetPathAllowingUniversalAccess(pathList, moduleName_, errorPath);
2014 }
2015 
ScrollByWithResult(float deltaX,float deltaY)2016 bool WebviewController::ScrollByWithResult(float deltaX, float deltaY)
2017 {
2018     bool enabled = false;
2019     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2020     if (nweb_ptr) {
2021         enabled = nweb_ptr->ScrollByWithResult(deltaX, deltaY);
2022     }
2023     return enabled;
2024 }
2025 
SetScrollable(bool enable,int32_t scrollType)2026 void WebviewController::SetScrollable(bool enable, int32_t scrollType)
2027 {
2028     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2029     if (!nweb_ptr) {
2030         return;
2031     }
2032     std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
2033     if (!setting) {
2034         return;
2035     }
2036     return setting->SetScrollable(enable, scrollType);
2037 }
2038 
SetType(int type)2039 void WebMessageExt::SetType(int type)
2040 {
2041     type_ = type;
2042     WebMessageType jsType = static_cast<WebMessageType>(type);
2043     NWebValue::Type nwebType = NWebValue::Type::NONE;
2044     switch (jsType) {
2045         case WebMessageType::STRING: {
2046             nwebType = NWebValue::Type::STRING;
2047             break;
2048         }
2049         case WebMessageType::NUMBER: {
2050             nwebType = NWebValue::Type::DOUBLE;
2051             break;
2052         }
2053         case WebMessageType::BOOLEAN: {
2054             nwebType = NWebValue::Type::BOOLEAN;
2055             break;
2056         }
2057         case WebMessageType::ARRAYBUFFER: {
2058             nwebType = NWebValue::Type::BINARY;
2059             break;
2060         }
2061         case WebMessageType::ARRAY: {
2062             nwebType = NWebValue::Type::STRINGARRAY;
2063             break;
2064         }
2065         case WebMessageType::ERROR: {
2066             nwebType = NWebValue::Type::ERROR;
2067             break;
2068         }
2069         default: {
2070             nwebType = NWebValue::Type::NONE;
2071             break;
2072         }
2073     }
2074     if (data_) {
2075         data_->SetType(nwebType);
2076     }
2077 }
2078 
ConvertNwebType2JsType(NWebValue::Type type)2079 int WebMessageExt::ConvertNwebType2JsType(NWebValue::Type type)
2080 {
2081     WebMessageType jsType = WebMessageType::NOTSUPPORT;
2082     switch (type) {
2083         case NWebValue::Type::STRING: {
2084             jsType = WebMessageType::STRING;
2085             break;
2086         }
2087         case NWebValue::Type::DOUBLE:
2088         case NWebValue::Type::INTEGER: {
2089             jsType = WebMessageType::NUMBER;
2090             break;
2091         }
2092         case NWebValue::Type::BOOLEAN: {
2093             jsType = WebMessageType::BOOLEAN;
2094             break;
2095         }
2096         case NWebValue::Type::STRINGARRAY:
2097         case NWebValue::Type::DOUBLEARRAY:
2098         case NWebValue::Type::INT64ARRAY:
2099         case NWebValue::Type::BOOLEANARRAY: {
2100             jsType = WebMessageType::ARRAY;
2101             break;
2102         }
2103         case NWebValue::Type::BINARY: {
2104             jsType = WebMessageType::ARRAYBUFFER;
2105             break;
2106         }
2107         case NWebValue::Type::ERROR: {
2108             jsType = WebMessageType::ERROR;
2109             break;
2110         }
2111         default: {
2112             jsType = WebMessageType::NOTSUPPORT;
2113             break;
2114         }
2115     }
2116     return static_cast<int>(jsType);
2117 }
2118 
ScrollToWithAnime(float x,float y,int32_t duration)2119 void WebviewController::ScrollToWithAnime(float x, float y, int32_t duration)
2120 {
2121     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2122     if (nweb_ptr) {
2123         nweb_ptr->ScrollToWithAnime(x, y, duration);
2124     }
2125     return;
2126 }
2127 
ScrollByWithAnime(float deltaX,float deltaY,int32_t duration)2128 void WebviewController::ScrollByWithAnime(float deltaX, float deltaY, int32_t duration)
2129 {
2130     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2131     if (nweb_ptr) {
2132         nweb_ptr->ScrollByWithAnime(deltaX, deltaY, duration);
2133     }
2134     return;
2135 }
2136 
GetScrollOffset(float * offset_x,float * offset_y)2137 void WebviewController::GetScrollOffset(float* offset_x, float* offset_y)
2138 {
2139     auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2140     if (nweb_ptr) {
2141         nweb_ptr->GetScrollOffset(offset_x, offset_y);
2142     }
2143 }
2144 } // namespace NWeb
2145 } // namespace OHOS
2146