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