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 "nweb_napi_scope.h"
27 #include "ohos_resource_adapter_impl.h"
28
29 #include "native_arkweb_utils.h"
30 #include "native_interface_arkweb.h"
31 #include "native_media_player_impl.h"
32
33 #include "nweb_log.h"
34 #include "nweb_store_web_archive_callback.h"
35 #include "web_errors.h"
36 #include "webview_createpdf_execute_callback.h"
37 #include "webview_hasimage_callback.h"
38 #include "webview_javascript_execute_callback.h"
39 #include "webview_javascript_result_callback.h"
40
41 #include "nweb_precompile_callback.h"
42 #include "nweb_cache_options_impl.h"
43
44 #include "bundle_mgr_proxy.h"
45 #include "if_system_ability_manager.h"
46 #include "iservice_registry.h"
47 #include "parameters.h"
48 #include "system_ability_definition.h"
49 #include "../../../../ohos_interface/ohos_glue/base/include/ark_web_errno.h"
50
51 namespace {
52 constexpr int32_t PARAMZERO = 0;
53 constexpr int32_t PARAMONE = 1;
54 constexpr int32_t RESULT_COUNT = 2;
55 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
56 const std::string MODULE_NAME_PREFIX = "moduleName:";
57 } // namespace
58
59 namespace OHOS {
60 namespace NWeb {
61 namespace {
62 constexpr uint32_t URL_MAXIMUM = 2048;
63 const std::string EVENT_CONTROLLER_ATTACH_STATE_CHANGE = "controllerAttachStateChange";
64 const std::string EVENT_WAIT_FOR_ATTACH = "waitForAttach";
65
66 struct WaitForAttachParam {
67 napi_async_work asyncWork;
68 napi_deferred deferred;
69 int32_t timeout;
70 WebviewController* webviewController;
71 int32_t state;
72 };
73
GetAppBundleNameAndModuleName(std::string & bundleName,std::string & moduleName)74 bool GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleName)
75 {
76 static std::string applicationBundleName;
77 static std::string applicationModuleName;
78 if (!applicationBundleName.empty() && !applicationModuleName.empty()) {
79 bundleName = applicationBundleName;
80 moduleName = applicationModuleName;
81 return true;
82 }
83 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
84 AbilityRuntime::ApplicationContext::GetApplicationContext();
85 if (!context) {
86 WVLOG_E("Failed to get application context.");
87 return false;
88 }
89 auto resourceManager = context->GetResourceManager();
90 if (!resourceManager) {
91 WVLOG_E("Failed to get resource manager.");
92 return false;
93 }
94 applicationBundleName = resourceManager->bundleInfo.first;
95 applicationModuleName = resourceManager->bundleInfo.second;
96 bundleName = applicationBundleName;
97 moduleName = applicationModuleName;
98 WVLOG_D("application bundleName: %{public}s, moduleName: %{public}s", bundleName.c_str(), moduleName.c_str());
99 return true;
100 }
101 }
102 using namespace NWebError;
103 std::mutex g_objectMtx;
104 std::unordered_map<int32_t, WebviewController*> g_webview_controller_map;
105 std::string WebviewController::customeSchemeCmdLine_ = "";
106 bool WebviewController::existNweb_ = false;
107 bool WebviewController::webDebuggingAccess_ = OHOS::system::GetBoolParameter("web.debug.devtools", false);
108 int32_t WebviewController::webDebuggingPort_ = 0;
109 std::set<std::string> WebviewController::webTagSet_;
110 int32_t WebviewController::webTagStrId_ = 0;
111 std::map<std::string, WebSchemeHandler*> WebviewController::webServiceWorkerSchemeHandlerMap_;
112
WebviewController(int32_t nwebId)113 WebviewController::WebviewController(int32_t nwebId) : nwebId_(nwebId)
114 {
115 if (IsInit()) {
116 std::unique_lock<std::mutex> lk(g_objectMtx);
117 g_webview_controller_map.emplace(nwebId, this);
118 }
119 }
120
WebviewController(const std::string & webTag)121 WebviewController::WebviewController(const std::string& webTag) : webTag_(webTag)
122 {
123 NWebHelper::Instance().SetWebTag(-1, webTag_.c_str());
124 }
125
~WebviewController()126 WebviewController::~WebviewController()
127 {
128 std::unique_lock<std::mutex> lk(g_objectMtx);
129 g_webview_controller_map.erase(nwebId_);
130
131 {
132 std::unique_lock<std::mutex> attachLock(attachMtx_);
133 attachState_ = AttachState::ATTACHED;
134 attachCond_.notify_all();
135 }
136
137 for (auto& [eventName, regObjs] : attachEventRegisterInfo_) {
138 for (auto& regObj : regObjs) {
139 if (regObj.m_regHanderRef != nullptr) {
140 napi_delete_reference(regObj.m_regEnv, regObj.m_regHanderRef);
141 regObj.m_regHanderRef = nullptr;
142 }
143 }
144 }
145 attachEventRegisterInfo_.clear();
146 }
147
TriggerStateChangeCallback(const std::string & type)148 void WebviewController::TriggerStateChangeCallback(const std::string& type)
149 {
150 auto iter = attachEventRegisterInfo_.find(type);
151 if (iter == attachEventRegisterInfo_.end()) {
152 WVLOG_D("WebviewController::TriggerStateChangeCallback event %{public}s not found.",
153 type.c_str());
154 return;
155 }
156
157 const std::vector<WebRegObj>& regObjs = iter->second;
158 for (const auto& regObj : regObjs) {
159 if (!regObj.m_isMarked){
160 napi_env env = regObj.m_regEnv;
161 napi_value handler = nullptr;
162 napi_get_reference_value(env, regObj.m_regHanderRef, &handler);
163
164 if (handler == nullptr) {
165 WVLOG_E("handler for event %{public}s is null.", type.c_str());
166 continue;
167 }
168
169 napi_value jsState = nullptr;
170 napi_create_int32(env, static_cast<int32_t>(attachState_), &jsState);
171
172 napi_value undefined;
173 napi_get_undefined(env, &undefined);
174
175 napi_call_function(env, nullptr, handler, 1, &jsState, &undefined);
176 }
177 }
178 for (auto it = iter->second.begin(); it != iter->second.end();) {
179 if (it->m_isMarked) {
180 napi_delete_reference(it->m_regEnv, it->m_regHanderRef);
181 it = iter->second.erase(it);
182 } else {
183 ++it;
184 }
185 }
186 }
187
SetWebId(int32_t nwebId)188 void WebviewController::SetWebId(int32_t nwebId)
189 {
190 nwebId_ = nwebId;
191 std::unique_lock<std::mutex> lk(g_objectMtx);
192 g_webview_controller_map.emplace(nwebId, this);
193
194 if (webTag_.empty()) {
195 WVLOG_I("native webtag is empty, don't care because it's not a native instance");
196 return;
197 }
198
199 AttachState prevState = attachState_;
200 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
201 if (nweb_ptr) {
202 OH_NativeArkWeb_BindWebTagToWebInstance(webTag_.c_str(), nweb_ptr);
203 NWebHelper::Instance().SetWebTag(nwebId_, webTag_.c_str());
204 {
205 std::unique_lock<std::mutex> attachLock(attachMtx_);
206 attachState_ = AttachState::ATTACHED;
207 attachCond_.notify_all();
208 }
209 if (prevState != attachState_) {
210 TriggerStateChangeCallback(EVENT_CONTROLLER_ATTACH_STATE_CHANGE);
211 }
212 }
213 SetNWebJavaScriptResultCallBack();
214 NativeArkWeb_OnValidCallback validCallback = OH_NativeArkWeb_GetJavaScriptProxyValidCallback(webTag_.c_str());
215 if (validCallback) {
216 WVLOG_I("native validCallback start to call");
217 (*validCallback)(webTag_.c_str());
218 } else {
219 WVLOG_W("native validCallback is null, callback nothing");
220 }
221 }
222
SetWebDetach(int32_t nwebId)223 void WebviewController::SetWebDetach(int32_t nwebId)
224 {
225 if (nwebId != nwebId_) {
226 WVLOG_W("web detach nwebId is not equal, detach is %{public}d, current is %{public}d", nwebId, nwebId_);
227 return;
228 }
229
230 if (attachState_ != AttachState::NOT_ATTACHED) {
231 attachState_ = AttachState::NOT_ATTACHED;
232 TriggerStateChangeCallback(EVENT_CONTROLLER_ATTACH_STATE_CHANGE);
233 }
234 }
235
FromID(int32_t nwebId)236 WebviewController* WebviewController::FromID(int32_t nwebId)
237 {
238 std::unique_lock<std::mutex> lk(g_objectMtx);
239 if (auto it = g_webview_controller_map.find(nwebId); it != g_webview_controller_map.end()) {
240 auto control = it->second;
241 return control;
242 }
243 return nullptr;
244 }
245
InnerCompleteWindowNew(int32_t parentNwebId)246 void WebviewController::InnerCompleteWindowNew(int32_t parentNwebId)
247 {
248 WVLOG_D("WebviewController::InnerCompleteWindowNew parentNwebId == "
249 "%{public}d ",
250 parentNwebId);
251 if (parentNwebId < 0) {
252 WVLOG_E("WebviewController::InnerCompleteWindowNew parentNwebId == %{public}d "
253 "error",
254 parentNwebId);
255 return;
256 }
257 auto parentControl = FromID(parentNwebId);
258 if (!parentControl || !(parentControl->javaScriptResultCb_)) {
259 WVLOG_E("WebviewController::InnerCompleteWindowNew parentControl or "
260 "javaScriptResultCb_ is null");
261 return;
262 }
263
264 auto parNamedObjs = parentControl->javaScriptResultCb_->GetNamedObjects();
265
266 auto currentControl = FromID(nwebId_);
267 if (!currentControl || !(currentControl->javaScriptResultCb_)) {
268 WVLOG_E("WebviewController::InnerCompleteWindowNew currentControl or "
269 "javaScriptResultCb_ is null");
270 return;
271 }
272
273 std::unique_lock<std::mutex> lock(webMtx_);
274 {
275 auto curNamedObjs = currentControl->javaScriptResultCb_->GetNamedObjects();
276 SetNWebJavaScriptResultCallBack();
277 for (auto it = parNamedObjs.begin(); it != parNamedObjs.end(); it++) {
278 if (curNamedObjs.find(it->first) != curNamedObjs.end()) {
279 continue;
280 }
281 if (it->second && IsInit()) {
282 RegisterJavaScriptProxyParam param;
283 param.env = it->second->GetEnv();
284 param.obj = it->second->GetValue();
285 param.objName = it->first;
286 param.syncMethodList = it->second->GetSyncMethodNames();
287 param.asyncMethodList = it->second->GetAsyncMethodNames();
288 param.permission = it->second->GetPermission();
289 RegisterJavaScriptProxy(param);
290 }
291 }
292 }
293 }
294
IsInit() const295 bool WebviewController::IsInit() const
296 {
297 return NWebHelper::Instance().GetNWeb(nwebId_) ? true : false;
298 }
299
AccessForward() const300 bool WebviewController::AccessForward() const
301 {
302 bool access = false;
303 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
304 if (nweb_ptr) {
305 access = nweb_ptr->IsNavigateForwardAllowed();
306 } else {
307 WVLOG_E("WebviewController::AccessForward nweb_ptr is null");
308 }
309 return access;
310 }
311
AccessBackward() const312 bool WebviewController::AccessBackward() const
313 {
314 bool access = false;
315 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
316 if (nweb_ptr) {
317 access = nweb_ptr->IsNavigatebackwardAllowed();
318 }
319 return access;
320 }
321
AccessStep(int32_t step) const322 bool WebviewController::AccessStep(int32_t step) const
323 {
324 bool access = false;
325 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
326 if (nweb_ptr) {
327 access = nweb_ptr->CanNavigateBackOrForward(step);
328 }
329 return access;
330 }
331
ClearHistory()332 void WebviewController::ClearHistory()
333 {
334 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
335 if (nweb_ptr) {
336 nweb_ptr->DeleteNavigateHistory();
337 }
338 }
339
Forward()340 void WebviewController::Forward()
341 {
342 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
343 if (nweb_ptr) {
344 nweb_ptr->NavigateForward();
345 }
346 }
347
Backward()348 void WebviewController::Backward()
349 {
350 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
351 if (nweb_ptr) {
352 nweb_ptr->NavigateBack();
353 }
354 }
355
OnActive()356 void WebviewController::OnActive()
357 {
358 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
359 if (nweb_ptr) {
360 nweb_ptr->OnContinue();
361 }
362 }
363
OnInactive()364 void WebviewController::OnInactive()
365 {
366 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
367 if (nweb_ptr) {
368 nweb_ptr->OnPause();
369 }
370 }
371
Refresh()372 void WebviewController::Refresh()
373 {
374 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
375 if (nweb_ptr) {
376 nweb_ptr->Reload();
377 }
378 }
379
ZoomIn()380 ErrCode WebviewController::ZoomIn()
381 {
382 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
383 if (!nweb_ptr) {
384 return INIT_ERROR;
385 }
386 ErrCode result = NWebError::NO_ERROR;
387 result = nweb_ptr->ZoomIn();
388
389 return result;
390 }
391
ZoomOut()392 ErrCode WebviewController::ZoomOut()
393 {
394 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
395 if (!nweb_ptr) {
396 return INIT_ERROR;
397 }
398 ErrCode result = NWebError::NO_ERROR;
399 result = nweb_ptr->ZoomOut();
400
401 return result;
402 }
403
GetWebId() const404 int32_t WebviewController::GetWebId() const
405 {
406 int32_t webId = -1;
407 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
408 if (nweb_ptr) {
409 webId = static_cast<int32_t>(nweb_ptr->GetWebId());
410 }
411 return webId;
412 }
413
GetUserAgent()414 std::string WebviewController::GetUserAgent()
415 {
416 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
417 if (!nweb_ptr) {
418 return "";
419 }
420 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
421 if (!setting) {
422 return "";
423 }
424 return setting->DefaultUserAgent();
425 }
426
GetCustomUserAgent() const427 std::string WebviewController::GetCustomUserAgent() const
428 {
429 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
430 if (!nweb_ptr) {
431 return "";
432 }
433 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
434 if (!setting) {
435 return "";
436 }
437 return setting->UserAgent();
438 }
439
SetCustomUserAgent(const std::string & userAgent)440 ErrCode WebviewController::SetCustomUserAgent(const std::string& userAgent)
441 {
442 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
443 if (!nweb_ptr) {
444 return NWebError::INIT_ERROR;
445 }
446 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
447 if (!setting) {
448 return NWebError::INIT_ERROR;
449 }
450 setting->PutUserAgent(userAgent);
451 return NWebError::NO_ERROR;
452 }
453
GetTitle()454 std::string WebviewController::GetTitle()
455 {
456 std::string title = "";
457 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
458 if (nweb_ptr) {
459 title = nweb_ptr->Title();
460 }
461 return title;
462 }
463
GetProgress()464 int32_t WebviewController::GetProgress()
465 {
466 int32_t progress = 0;
467 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
468 if (nweb_ptr) {
469 progress = nweb_ptr->PageLoadProgress();
470 }
471 return progress;
472 }
473
GetPageHeight()474 int32_t WebviewController::GetPageHeight()
475 {
476 int32_t pageHeight = 0;
477 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
478 if (nweb_ptr) {
479 pageHeight = nweb_ptr->ContentHeight();
480 }
481 return pageHeight;
482 }
483
BackOrForward(int32_t step)484 ErrCode WebviewController::BackOrForward(int32_t step)
485 {
486 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
487 if (!nweb_ptr) {
488 return INIT_ERROR;
489 }
490
491 nweb_ptr->NavigateBackOrForward(step);
492 return NWebError::NO_ERROR;
493 }
494
StoreWebArchiveCallback(const std::string & baseName,bool autoName,napi_env env,napi_ref jsCallback)495 void WebviewController::StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env,
496 napi_ref jsCallback)
497 {
498 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
499 if (!nweb_ptr) {
500 napi_value setResult[RESULT_COUNT] = {0};
501 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
502 napi_get_null(env, &setResult[PARAMONE]);
503
504 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
505 napi_value callback = nullptr;
506 napi_get_reference_value(env, jsCallback, &callback);
507 napi_value callbackResult = nullptr;
508 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
509 napi_delete_reference(env, jsCallback);
510 return;
511 }
512
513 if (jsCallback == nullptr) {
514 return;
515 }
516
517 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
518 callbackImpl->SetCallBack([env, jCallback = std::move(jsCallback)](std::string result) {
519 if (!env) {
520 return;
521 }
522 NApiScope scope(env);
523 if (!scope.IsVaild()) {
524 return;
525 }
526
527 napi_value setResult[RESULT_COUNT] = {0};
528 if (result.empty()) {
529 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
530 napi_get_null(env, &setResult[PARAMONE]);
531 } else {
532 napi_get_undefined(env, &setResult[PARAMZERO]);
533 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
534 }
535 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
536 napi_value callback = nullptr;
537 napi_get_reference_value(env, jCallback, &callback);
538 napi_value callbackResult = nullptr;
539 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
540
541 napi_delete_reference(env, jCallback);
542 });
543 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
544 return;
545 }
546
StoreWebArchivePromise(const std::string & baseName,bool autoName,napi_env env,napi_deferred deferred)547 void WebviewController::StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env,
548 napi_deferred deferred)
549 {
550 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
551 if (!nweb_ptr) {
552 napi_value jsResult = nullptr;
553 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
554 napi_reject_deferred(env, deferred, jsResult);
555 return;
556 }
557
558 if (deferred == nullptr) {
559 return;
560 }
561
562 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
563 callbackImpl->SetCallBack([env, deferred](std::string result) {
564 if (!env) {
565 return;
566 }
567 NApiScope scope(env);
568 if (!scope.IsVaild()) {
569 return;
570 }
571
572 napi_value setResult[RESULT_COUNT] = {0};
573 setResult[PARAMZERO] = NWebError::BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
574 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
575 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
576 if (!result.empty()) {
577 napi_resolve_deferred(env, deferred, args[PARAMONE]);
578 } else {
579 napi_reject_deferred(env, deferred, args[PARAMZERO]);
580 }
581 });
582 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
583 return;
584 }
585
CreateWebMessagePorts()586 std::vector<std::string> WebviewController::CreateWebMessagePorts()
587 {
588 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
589 if (!nweb_ptr) {
590 std::vector<std::string> empty;
591 return empty;
592 }
593
594 return nweb_ptr->CreateWebMessagePorts();
595 }
596
PostWebMessage(std::string & message,std::vector<std::string> & ports,std::string & targetUrl)597 ErrCode WebviewController::PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl)
598 {
599 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
600 if (!nweb_ptr) {
601 return INIT_ERROR;
602 }
603
604 nweb_ptr->PostWebMessage(message, ports, targetUrl);
605 return NWebError::NO_ERROR;
606 }
607
GetHitTestValue()608 std::shared_ptr<HitTestResult> WebviewController::GetHitTestValue()
609 {
610 std::shared_ptr<HitTestResult> nwebResult;
611 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
612 if (nweb_ptr) {
613 nwebResult = nweb_ptr->GetHitTestResult();
614 if (nwebResult) {
615 nwebResult->SetType(ConverToWebHitTestType(nwebResult->GetType()));
616 }
617 }
618 return nwebResult;
619 }
620
RequestFocus()621 void WebviewController::RequestFocus()
622 {
623 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
624 if (nweb_ptr) {
625 nweb_ptr->OnFocus();
626 }
627 }
628
GenerateWebTag()629 std::string WebviewController::GenerateWebTag()
630 {
631 std::string webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
632 while (WebviewController::webTagSet_.find(webTag) != WebviewController::webTagSet_.end()) {
633 WebviewController::webTagStrId_++;
634 webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
635 }
636 return webTag;
637 }
638
GetRawFileUrl(const std::string & fileName,const std::string & bundleName,const std::string & moduleName,std::string & result) const639 bool WebviewController::GetRawFileUrl(const std::string &fileName,
640 const std::string& bundleName, const std::string& moduleName, std::string &result) const
641 {
642 if (fileName.empty()) {
643 WVLOG_E("File name is empty.");
644 return false;
645 }
646 if (hapPath_.empty()) {
647 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
648 AbilityRuntime::ApplicationContext::GetApplicationContext();
649 std::string packagePath = "file:///" + context->GetBundleCodeDir() + "/";
650 std::string contextBundleName = context->GetBundleName() + "/";
651 std::shared_ptr<AppExecFwk::ApplicationInfo> appInfo = context->GetApplicationInfo();
652 std::string entryDir = appInfo->entryDir;
653 bool isStage = entryDir.find("entry") == std::string::npos ? false : true;
654 result = isStage ? packagePath + "entry/resources/rawfile/" + fileName :
655 packagePath + contextBundleName + "assets/entry/resources/rawfile/" + fileName;
656 } else {
657 std::string appBundleName;
658 std::string appModuleName;
659 result = "resource://RAWFILE/";
660 if (!bundleName.empty() && !moduleName.empty() &&
661 GetAppBundleNameAndModuleName(appBundleName, appModuleName)) {
662 if (appBundleName != bundleName || appModuleName != moduleName) {
663 result += BUNDLE_NAME_PREFIX + bundleName + "/" + MODULE_NAME_PREFIX + moduleName + "/";
664 }
665 }
666 result += fileName;
667 }
668 WVLOG_D("The parsed url is: ***");
669 return true;
670 }
671
ParseUrl(napi_env env,napi_value urlObj,std::string & result) const672 bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result) const
673 {
674 napi_valuetype valueType = napi_null;
675 napi_typeof(env, urlObj, &valueType);
676 if ((valueType != napi_object) && (valueType != napi_string)) {
677 WVLOG_E("Unable to parse url object.");
678 return false;
679 }
680 if (valueType == napi_string) {
681 NapiParseUtils::ParseString(env, urlObj, result);
682 WVLOG_D("The parsed url is: ***");
683 return true;
684 }
685 napi_value type = nullptr;
686 napi_valuetype typeVlueType = napi_null;
687 napi_get_named_property(env, urlObj, "type", &type);
688 napi_typeof(env, type, &typeVlueType);
689 if (typeVlueType == napi_number) {
690 int32_t typeInteger;
691 NapiParseUtils::ParseInt32(env, type, typeInteger);
692 if (typeInteger == static_cast<int>(ResourceType::RAWFILE)) {
693 return ParseRawFileUrl(env, urlObj, result);
694 } else if (typeInteger == static_cast<int>(ResourceType::STRING)) {
695 if (!GetResourceUrl(env, urlObj, result)) {
696 WVLOG_E("Unable to parse string from url object.");
697 return false;
698 }
699 return true;
700 }
701 WVLOG_E("The type parsed from url object is not RAWFILE.");
702 return false;
703 }
704 WVLOG_E("Unable to parse type from url object.");
705 return false;
706 }
707
ParseRawFileUrl(napi_env env,napi_value urlObj,std::string & result) const708 bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const
709 {
710 napi_value paraArray = nullptr;
711 napi_get_named_property(env, urlObj, "params", ¶Array);
712 bool isArray = false;
713 napi_is_array(env, paraArray, &isArray);
714 if (!isArray) {
715 WVLOG_E("Unable to parse parameter array from url object.");
716 return false;
717 }
718 napi_value fileNameObj;
719 napi_value bundleNameObj;
720 napi_value moduleNameObj;
721 std::string fileName;
722 std::string bundleName;
723 std::string moduleName;
724 napi_get_element(env, paraArray, 0, &fileNameObj);
725 napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj);
726 napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj);
727 NapiParseUtils::ParseString(env, fileNameObj, fileName);
728 NapiParseUtils::ParseString(env, bundleNameObj, bundleName);
729 NapiParseUtils::ParseString(env, moduleNameObj, moduleName);
730 return GetRawFileUrl(fileName, bundleName, moduleName, result);
731 }
732
GetResourceUrl(napi_env env,napi_value urlObj,std::string & result) const733 bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const
734 {
735 napi_value resIdObj = nullptr;
736 napi_value bundleNameObj = nullptr;
737 napi_value moduleNameObj = nullptr;
738
739 int32_t resId;
740 std::string bundleName;
741 std::string moduleName;
742
743 if ((napi_get_named_property(env, urlObj, "id", &resIdObj) != napi_ok) ||
744 (napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj) != napi_ok) ||
745 (napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj) != napi_ok)) {
746 return false;
747 }
748
749 if (!NapiParseUtils::ParseInt32(env, resIdObj, resId) ||
750 !NapiParseUtils::ParseString(env, bundleNameObj, bundleName) ||
751 !NapiParseUtils::ParseString(env, moduleNameObj, moduleName)) {
752 return false;
753 }
754
755 if (OhosResourceAdapterImpl::GetResourceString(bundleName, moduleName, resId, result)) {
756 return true;
757 }
758 return false;
759 }
760
PostUrl(std::string & url,std::vector<char> & postData)761 ErrCode WebviewController::PostUrl(std::string& url, std::vector<char>& postData)
762 {
763 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
764 if (!nweb_ptr) {
765 return INIT_ERROR;
766 }
767 return nweb_ptr->PostUrl(url, postData);
768 }
769
LoadUrl(std::string url)770 ErrCode WebviewController::LoadUrl(std::string url)
771 {
772 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
773 if (!nweb_ptr) {
774 return INIT_ERROR;
775 }
776 return nweb_ptr->Load(url);
777 }
778
LoadUrl(std::string url,std::map<std::string,std::string> httpHeaders)779 ErrCode WebviewController::LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders)
780 {
781 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
782 if (!nweb_ptr) {
783 return INIT_ERROR;
784 }
785 return nweb_ptr->Load(url, httpHeaders);
786 }
787
LoadData(std::string data,std::string mimeType,std::string encoding,std::string baseUrl,std::string historyUrl)788 ErrCode WebviewController::LoadData(std::string data, std::string mimeType, std::string encoding,
789 std::string baseUrl, std::string historyUrl)
790 {
791 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
792 if (!nweb_ptr) {
793 return INIT_ERROR;
794 }
795 if (baseUrl.empty() && historyUrl.empty()) {
796 return nweb_ptr->LoadWithData(data, mimeType, encoding);
797 }
798 return nweb_ptr->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
799 }
800
ConverToWebHitTestType(int hitType)801 int WebviewController::ConverToWebHitTestType(int hitType)
802 {
803 WebHitTestType webHitType;
804 switch (hitType) {
805 case HitTestResult::UNKNOWN_TYPE:
806 webHitType = WebHitTestType::UNKNOWN;
807 break;
808 case HitTestResult::ANCHOR_TYPE:
809 webHitType = WebHitTestType::HTTP;
810 break;
811 case HitTestResult::PHONE_TYPE:
812 webHitType = WebHitTestType::PHONE;
813 break;
814 case HitTestResult::GEO_TYPE:
815 webHitType = WebHitTestType::MAP;
816 break;
817 case HitTestResult::EMAIL_TYPE:
818 webHitType = WebHitTestType::EMAIL;
819 break;
820 case HitTestResult::IMAGE_TYPE:
821 webHitType = WebHitTestType::IMG;
822 break;
823 case HitTestResult::IMAGE_ANCHOR_TYPE:
824 webHitType = WebHitTestType::HTTP_IMG;
825 break;
826 case HitTestResult::SRC_ANCHOR_TYPE:
827 webHitType = WebHitTestType::HTTP;
828 break;
829 case HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
830 webHitType = WebHitTestType::HTTP_IMG;
831 break;
832 case HitTestResult::EDIT_TEXT_TYPE:
833 webHitType = WebHitTestType::EDIT;
834 break;
835 default:
836 webHitType = WebHitTestType::UNKNOWN;
837 break;
838 }
839 return static_cast<int>(webHitType);
840 }
841
GetHitTest()842 int WebviewController::GetHitTest()
843 {
844 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
845 if (nweb_ptr) {
846 std::shared_ptr<HitTestResult> nwebResult = nweb_ptr->GetHitTestResult();
847 if (nwebResult) {
848 return ConverToWebHitTestType(nwebResult->GetType());
849 } else {
850 return ConverToWebHitTestType(HitTestResult::UNKNOWN_TYPE);
851 }
852 }
853 return static_cast<int>(WebHitTestType::UNKNOWN);
854 }
855
856
ClearMatches()857 void WebviewController::ClearMatches()
858 {
859 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
860 if (nweb_ptr) {
861 nweb_ptr->ClearMatches();
862 }
863 }
864
SearchNext(bool forward)865 void WebviewController::SearchNext(bool forward)
866 {
867 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
868 if (nweb_ptr) {
869 nweb_ptr->FindNext(forward);
870 }
871 }
872
EnableSafeBrowsing(bool enable)873 void WebviewController::EnableSafeBrowsing(bool enable)
874 {
875 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
876 if (nweb_ptr) {
877 nweb_ptr->EnableSafeBrowsing(enable);
878 }
879 }
880
IsSafeBrowsingEnabled() const881 bool WebviewController::IsSafeBrowsingEnabled() const
882 {
883 bool isSafeBrowsingEnabled = false;
884 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
885 if (nweb_ptr) {
886 isSafeBrowsingEnabled = nweb_ptr->IsSafeBrowsingEnabled();
887 }
888 return isSafeBrowsingEnabled;
889 }
890
SearchAllAsync(const std::string & searchString)891 void WebviewController::SearchAllAsync(const std::string& searchString)
892 {
893 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
894 if (nweb_ptr) {
895 nweb_ptr->FindAllAsync(searchString);
896 }
897 }
898
ClearSslCache()899 void WebviewController::ClearSslCache()
900 {
901 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
902 if (nweb_ptr) {
903 nweb_ptr->ClearSslCache();
904 }
905 }
906
ClearClientAuthenticationCache()907 void WebviewController::ClearClientAuthenticationCache()
908 {
909 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
910 if (nweb_ptr) {
911 nweb_ptr->ClearClientAuthenticationCache();
912 }
913 }
914
Stop()915 void WebviewController::Stop()
916 {
917 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
918 if (nweb_ptr) {
919 nweb_ptr->Stop();
920 }
921 }
922
Zoom(float factor)923 ErrCode WebviewController::Zoom(float factor)
924 {
925 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
926 if (!nweb_ptr) {
927 return INIT_ERROR;
928 }
929 ErrCode result = NWebError::NO_ERROR;
930 result = nweb_ptr->Zoom(factor);
931
932 return result;
933 }
934
DeleteJavaScriptRegister(const std::string & objName,const std::vector<std::string> & methodList)935 ErrCode WebviewController::DeleteJavaScriptRegister(const std::string& objName,
936 const std::vector<std::string>& methodList)
937 {
938 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
939 if (nweb_ptr) {
940 nweb_ptr->UnregisterArkJSfunction(objName, methodList);
941 }
942
943 if (javaScriptResultCb_) {
944 bool ret = javaScriptResultCb_->DeleteJavaScriptRegister(objName);
945 if (!ret) {
946 return CANNOT_DEL_JAVA_SCRIPT_PROXY;
947 }
948 }
949
950 return NWebError::NO_ERROR;
951 }
952
SetNWebJavaScriptResultCallBack()953 void WebviewController::SetNWebJavaScriptResultCallBack()
954 {
955 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
956 if (!nweb_ptr) {
957 return;
958 }
959
960 if (javaScriptResultCb_ && (javaScriptResultCb_->GetNWebId() == nwebId_)) {
961 return;
962 }
963
964 javaScriptResultCb_ = std::make_shared<WebviewJavaScriptResultCallBack>(nwebId_);
965 nweb_ptr->SetNWebJavaScriptResultCallBack(javaScriptResultCb_);
966 }
967
RegisterJavaScriptProxy(RegisterJavaScriptProxyParam & param)968 void WebviewController::RegisterJavaScriptProxy(RegisterJavaScriptProxyParam& param)
969 {
970 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
971 if (!nweb_ptr) {
972 WVLOG_E("WebviewController::RegisterJavaScriptProxy nweb_ptr is null");
973 return;
974 }
975 JavaScriptOb::ObjectID objId =
976 static_cast<JavaScriptOb::ObjectID>(JavaScriptOb::JavaScriptObjIdErrorCode::WEBCONTROLLERERROR);
977
978 if (!javaScriptResultCb_) {
979 WVLOG_E("WebviewController::RegisterJavaScriptProxy javaScriptResultCb_ is "
980 "null");
981 return;
982 }
983
984 if (param.syncMethodList.empty() && param.asyncMethodList.empty()) {
985 WVLOG_E("WebviewController::RegisterJavaScriptProxy all methodList are "
986 "empty");
987 return;
988 }
989
990 std::vector<std::string> allMethodList;
991 std::merge(param.syncMethodList.begin(), param.syncMethodList.end(),
992 param.asyncMethodList.begin(), param.asyncMethodList.end(),
993 std::back_inserter(allMethodList));
994
995 RegisterJavaScriptProxyParam param_tmp;
996 param_tmp.env = param.env;
997 param_tmp.obj = param.obj;
998 param_tmp.objName = param.objName;
999 param_tmp.syncMethodList = allMethodList;
1000 param_tmp.asyncMethodList = param.asyncMethodList;
1001 param_tmp.permission = param.permission;
1002 objId = javaScriptResultCb_->RegisterJavaScriptProxy(param_tmp);
1003
1004 nweb_ptr->RegisterArkJSfunction(param_tmp.objName, param_tmp.syncMethodList,
1005 std::vector<std::string>(), objId, param_tmp.permission);
1006 }
1007
RunJavaScriptCallback(const std::string & script,napi_env env,napi_ref jsCallback,bool extention)1008 void WebviewController::RunJavaScriptCallback(
1009 const std::string& script, napi_env env, napi_ref jsCallback, bool extention)
1010 {
1011 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1012 if (!nweb_ptr) {
1013 napi_value setResult[RESULT_COUNT] = {0};
1014 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1015 napi_get_null(env, &setResult[PARAMONE]);
1016
1017 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1018 napi_value callback = nullptr;
1019 napi_get_reference_value(env, jsCallback, &callback);
1020 napi_value callbackResult = nullptr;
1021 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1022 napi_delete_reference(env, jsCallback);
1023 return;
1024 }
1025
1026 if (jsCallback == nullptr) {
1027 return;
1028 }
1029
1030 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
1031 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
1032 }
1033
RunJavaScriptPromise(const std::string & script,napi_env env,napi_deferred deferred,bool extention)1034 void WebviewController::RunJavaScriptPromise(const std::string &script, napi_env env,
1035 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 return;
1043 }
1044
1045 if (deferred == nullptr) {
1046 return;
1047 }
1048
1049 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
1050 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
1051 }
1052
RunJavaScriptCallbackExt(const int fd,const size_t scriptLength,napi_env env,napi_ref jsCallback,bool extention)1053 void WebviewController::RunJavaScriptCallbackExt(
1054 const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention)
1055 {
1056 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1057 if (!nweb_ptr) {
1058 napi_value setResult[RESULT_COUNT] = {0};
1059 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1060 napi_get_null(env, &setResult[PARAMONE]);
1061
1062 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1063 napi_value callback = nullptr;
1064 napi_get_reference_value(env, jsCallback, &callback);
1065 napi_value callbackResult = nullptr;
1066 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1067 napi_delete_reference(env, jsCallback);
1068 close(fd);
1069 return;
1070 }
1071
1072 if (jsCallback == nullptr) {
1073 close(fd);
1074 return;
1075 }
1076
1077 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
1078 nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
1079 }
1080
RunJavaScriptPromiseExt(const int fd,const size_t scriptLength,napi_env env,napi_deferred deferred,bool extention)1081 void WebviewController::RunJavaScriptPromiseExt(
1082 const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention)
1083 {
1084 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1085 if (!nweb_ptr) {
1086 napi_value jsResult = nullptr;
1087 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1088 napi_reject_deferred(env, deferred, jsResult);
1089 close(fd);
1090 return;
1091 }
1092
1093 if (deferred == nullptr) {
1094 close(fd);
1095 return;
1096 }
1097
1098 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
1099 nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
1100 }
1101
CreatePDFCallbackExt(napi_env env,std::shared_ptr<NWebPDFConfigArgs> pdfConfig,napi_ref pdfCallback)1102 void WebviewController::CreatePDFCallbackExt(
1103 napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_ref pdfCallback)
1104 {
1105 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1106 if (!nweb_ptr) {
1107 napi_value setResult[RESULT_COUNT] = { 0 };
1108 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1109 napi_get_null(env, &setResult[PARAMONE]);
1110
1111 napi_value args[RESULT_COUNT] = { setResult[PARAMZERO], setResult[PARAMONE] };
1112 napi_value callback = nullptr;
1113 napi_get_reference_value(env, pdfCallback, &callback);
1114 napi_value callbackResult = nullptr;
1115 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1116 napi_delete_reference(env, pdfCallback);
1117 return;
1118 }
1119 if (pdfCallback == nullptr) {
1120 return;
1121 }
1122 auto callbackImpl = std::make_shared<WebviewCreatePDFExecuteCallback>(env, pdfCallback, nullptr);
1123 nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl);
1124 }
1125
CreatePDFPromiseExt(napi_env env,std::shared_ptr<NWebPDFConfigArgs> pdfConfig,napi_deferred deferred)1126 void WebviewController::CreatePDFPromiseExt(
1127 napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_deferred deferred)
1128 {
1129 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1130 if (!nweb_ptr) {
1131 napi_value pdfResult = nullptr;
1132 pdfResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1133 napi_reject_deferred(env, deferred, pdfResult);
1134 return;
1135 }
1136 if (deferred == nullptr) {
1137 return;
1138 }
1139 auto callbackImpl = std::make_shared<WebviewCreatePDFExecuteCallback>(env, nullptr, deferred);
1140 nweb_ptr->ExecuteCreatePDFExt(pdfConfig, callbackImpl);
1141 }
1142
GetUrl()1143 std::string WebviewController::GetUrl()
1144 {
1145 std::string url = "";
1146 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1147 if (nweb_ptr) {
1148 url = nweb_ptr->GetUrl();
1149 }
1150 return url;
1151 }
1152
GetOriginalUrl()1153 std::string WebviewController::GetOriginalUrl()
1154 {
1155 std::string url = "";
1156 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1157 if (nweb_ptr) {
1158 url = nweb_ptr->GetOriginalUrl();
1159 }
1160 return url;
1161 }
1162
TerminateRenderProcess() const1163 bool WebviewController::TerminateRenderProcess() const
1164 {
1165 bool ret = false;
1166 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1167 if (nweb_ptr) {
1168 ret = nweb_ptr->TerminateRenderProcess();
1169 }
1170 return ret;
1171 }
1172
PutNetworkAvailable(bool available)1173 void WebviewController::PutNetworkAvailable(bool available)
1174 {
1175 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1176 if (nweb_ptr) {
1177 nweb_ptr->PutNetworkAvailable(available);
1178 }
1179 }
1180
HasImagesCallback(napi_env env,napi_ref jsCallback)1181 ErrCode WebviewController::HasImagesCallback(napi_env env, napi_ref jsCallback)
1182 {
1183 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1184 if (!nweb_ptr) {
1185 napi_value setResult[RESULT_COUNT] = {0};
1186 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1187 napi_get_null(env, &setResult[PARAMONE]);
1188
1189 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1190 napi_value callback = nullptr;
1191 napi_get_reference_value(env, jsCallback, &callback);
1192 napi_value callbackResult = nullptr;
1193 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1194 napi_delete_reference(env, jsCallback);
1195 return NWebError::INIT_ERROR;
1196 }
1197
1198 if (jsCallback == nullptr) {
1199 return NWebError::PARAM_CHECK_ERROR;
1200 }
1201
1202 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, jsCallback, nullptr);
1203 nweb_ptr->HasImages(callbackImpl);
1204 return NWebError::NO_ERROR;
1205 }
1206
HasImagesPromise(napi_env env,napi_deferred deferred)1207 ErrCode WebviewController::HasImagesPromise(napi_env env, napi_deferred deferred)
1208 {
1209 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1210 if (!nweb_ptr) {
1211 napi_value jsResult = nullptr;
1212 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1213 napi_reject_deferred(env, deferred, jsResult);
1214 return NWebError::INIT_ERROR;
1215 }
1216
1217 if (deferred == nullptr) {
1218 return NWebError::PARAM_CHECK_ERROR;
1219 }
1220
1221 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, nullptr, deferred);
1222 nweb_ptr->HasImages(callbackImpl);
1223 return NWebError::NO_ERROR;
1224 }
1225
RemoveCache(bool includeDiskFiles)1226 void WebviewController::RemoveCache(bool includeDiskFiles)
1227 {
1228 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1229 if (nweb_ptr) {
1230 nweb_ptr->RemoveCache(includeDiskFiles);
1231 }
1232 }
1233
GetHistoryList()1234 std::shared_ptr<NWebHistoryList> WebviewController::GetHistoryList()
1235 {
1236 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1237 if (!nweb_ptr) {
1238 return nullptr;
1239 }
1240 return nweb_ptr->GetHistoryList();
1241 }
1242
GetFavicon(const void ** data,size_t & width,size_t & height,ImageColorType & colorType,ImageAlphaType & alphaType) const1243 bool WebviewController::GetFavicon(
1244 const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const
1245 {
1246 bool isGetFavicon = false;
1247 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1248 if (nweb_ptr) {
1249 isGetFavicon = nweb_ptr->GetFavicon(data, width, height, colorType, alphaType);
1250 }
1251 return isGetFavicon;
1252 }
1253
SerializeWebState()1254 std::vector<uint8_t> WebviewController::SerializeWebState()
1255 {
1256 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1257 if (nweb_ptr) {
1258 return nweb_ptr->SerializeWebState();
1259 }
1260 std::vector<uint8_t> empty;
1261 return empty;
1262 }
1263
RestoreWebState(const std::vector<uint8_t> & state) const1264 bool WebviewController::RestoreWebState(const std::vector<uint8_t> &state) const
1265 {
1266 bool isRestored = false;
1267 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1268 if (nweb_ptr) {
1269 isRestored = nweb_ptr->RestoreWebState(state);
1270 }
1271 return isRestored;
1272 }
1273
ScrollPageDown(bool bottom)1274 void WebviewController::ScrollPageDown(bool bottom)
1275 {
1276 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1277 if (nweb_ptr) {
1278 nweb_ptr->PageDown(bottom);
1279 }
1280 return;
1281 }
1282
ScrollPageUp(bool top)1283 void WebviewController::ScrollPageUp(bool top)
1284 {
1285 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1286 if (nweb_ptr) {
1287 nweb_ptr->PageUp(top);
1288 }
1289 return;
1290 }
1291
ScrollTo(float x,float y)1292 void WebviewController::ScrollTo(float x, float y)
1293 {
1294 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1295 if (nweb_ptr) {
1296 nweb_ptr->ScrollTo(x, y);
1297 }
1298 return;
1299 }
1300
ScrollBy(float deltaX,float deltaY)1301 void WebviewController::ScrollBy(float deltaX, float deltaY)
1302 {
1303 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1304 if (nweb_ptr) {
1305 nweb_ptr->ScrollBy(deltaX, deltaY);
1306 }
1307 return;
1308 }
1309
SlideScroll(float vx,float vy)1310 void WebviewController::SlideScroll(float vx, float vy)
1311 {
1312 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1313 if (nweb_ptr) {
1314 nweb_ptr->SlideScroll(vx, vy);
1315 }
1316 return;
1317 }
1318
SetScrollable(bool enable)1319 void WebviewController::SetScrollable(bool enable)
1320 {
1321 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1322 if (!nweb_ptr) {
1323 return;
1324 }
1325 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1326 if (!setting) {
1327 return;
1328 }
1329 return setting->SetScrollable(enable);
1330 }
1331
GetScrollable() const1332 bool WebviewController::GetScrollable() const
1333 {
1334 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1335 if (!nweb_ptr) {
1336 return true;
1337 }
1338 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1339 if (!setting) {
1340 return true;
1341 }
1342 return setting->GetScrollable();
1343 }
1344
InnerSetHapPath(const std::string & hapPath)1345 void WebviewController::InnerSetHapPath(const std::string &hapPath)
1346 {
1347 hapPath_ = hapPath;
1348 }
1349
InnerSetFavicon(napi_env env,napi_value favicon)1350 void WebviewController::InnerSetFavicon(napi_env env, napi_value favicon)
1351 {
1352 favicon_.CreateReference(env, favicon);
1353 }
1354
InnerGetFavicon(napi_env env)1355 napi_value WebviewController::InnerGetFavicon(napi_env env)
1356 {
1357 return favicon_.GetRefValue();
1358 }
1359
GetCertChainDerData(std::vector<std::string> & certChainDerData) const1360 bool WebviewController::GetCertChainDerData(std::vector<std::string> &certChainDerData) const
1361 {
1362 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1363 if (!nweb_ptr) {
1364 WVLOG_E("GetCertChainDerData failed, nweb ptr is null");
1365 return false;
1366 }
1367
1368 return nweb_ptr->GetCertChainDerData(certChainDerData, true);
1369 }
1370
SetAudioMuted(bool muted)1371 ErrCode WebviewController::SetAudioMuted(bool muted)
1372 {
1373 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1374 if (!nweb_ptr) {
1375 return NWebError::INIT_ERROR;
1376 }
1377
1378 nweb_ptr->SetAudioMuted(muted);
1379 return NWebError::NO_ERROR;
1380 }
1381
PrefetchPage(std::string & url,std::map<std::string,std::string> additionalHttpHeaders)1382 ErrCode WebviewController::PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders)
1383 {
1384 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1385 if (!nweb_ptr) {
1386 return NWebError::INIT_ERROR;
1387 }
1388
1389 nweb_ptr->PrefetchPage(url, additionalHttpHeaders);
1390 return NWebError::NO_ERROR;
1391 }
1392
GetBool(uint32_t attrId)1393 bool WebPrintAttributes::GetBool(uint32_t attrId)
1394 {
1395 switch (attrId) {
1396 case NWEB_PRINT_ATTR_ID_IS_VALID:
1397 return true;
1398 case NWEB_PRINT_ATTR_ID_PAGE_IS_SEQUENTIAL:
1399 return attrs_.isSequential;
1400 case NWEB_PRINT_ATTR_ID_IS_LANDSCAPE:
1401 return attrs_.isLandscape;
1402 case NWEB_PRINT_ATTR_ID_HAS_OPTION:
1403 return attrs_.hasOption;
1404 default:
1405 break;
1406 }
1407
1408 return false;
1409 }
1410
GetUInt32(uint32_t attrId)1411 uint32_t WebPrintAttributes::GetUInt32(uint32_t attrId)
1412 {
1413 switch (attrId) {
1414 case NWEB_PRINT_ATTR_ID_COPY_NUMBER:
1415 return attrs_.copyNumber;
1416 case NWEB_PRINT_ATTR_ID_PAGE_RANGE_START:
1417 return attrs_.pageRange.startPage;
1418 case NWEB_PRINT_ATTR_ID_PAGE_RANGE_END:
1419 return attrs_.pageRange.endPage;
1420 case NWEB_PRINT_ATTR_ID_PAGE_SIZE_WIDTH:
1421 return attrs_.pageSize.width;
1422 case NWEB_PRINT_ATTR_ID_PAGE_SIZE_HEIGHT:
1423 return attrs_.pageSize.height;
1424 case NWEB_PRINT_ATTR_ID_COLOR_MODE:
1425 return attrs_.colorMode;
1426 case NWEB_PRINT_ATTR_ID_DUPLEX_MODE:
1427 return attrs_.duplexMode;
1428 case NWEB_PRINT_ATTR_ID_MARGIN_TOP:
1429 return attrs_.margin.top;
1430 case NWEB_PRINT_ATTR_ID_MARGIN_BOTTOM:
1431 return attrs_.margin.bottom;
1432 case NWEB_PRINT_ATTR_ID_MARGIN_LEFT:
1433 return attrs_.margin.left;
1434 case NWEB_PRINT_ATTR_ID_MARGIN_RIGHT:
1435 return attrs_.margin.right;
1436 default:
1437 break;
1438 }
1439 return 0;
1440 }
1441
GetString(uint32_t attrId)1442 std::string WebPrintAttributes::GetString(uint32_t attrId)
1443 {
1444 switch (attrId) {
1445 case NWEB_PRINT_ATTR_ID_OPTION:
1446 return attrs_.option;
1447 default:
1448 break;
1449 }
1450 return "";
1451 }
1452
GetUint32Vector(uint32_t attrId)1453 std::vector<uint32_t> WebPrintAttributes::GetUint32Vector(uint32_t attrId)
1454 {
1455 switch (attrId) {
1456 case NWEB_PRINT_ATTR_ID_PAGE_RANGE_ARRAY:
1457 return attrs_.pageRange.pages;
1458 default:
1459 break;
1460 }
1461 return std::vector<uint32_t>();
1462 }
1463
OnStartLayoutWrite(const std::string & jobId,const PrintAttributesAdapter & oldAttrs,const PrintAttributesAdapter & newAttrs,uint32_t fd,std::function<void (std::string,uint32_t)> writeResultCallback)1464 void WebPrintDocument::OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs,
1465 const PrintAttributesAdapter& newAttrs, uint32_t fd, std::function<void(std::string, uint32_t)> writeResultCallback)
1466 {
1467 if (printDocAdapterV2_) {
1468 std::shared_ptr<WebPrintWriteResultCallbackAdapterV2> callbackV2 =
1469 std::make_shared<WebPrintWriteResultCallbackAdapterV2>(writeResultCallback);
1470 auto oldAttributes = std::make_shared<WebPrintAttributes>(oldAttrs);
1471 auto newAttributes = std::make_shared<WebPrintAttributes>(newAttrs);
1472 printDocAdapterV2_->OnStartLayoutWrite(jobId, oldAttributes, newAttributes, fd, callbackV2);
1473 return;
1474 }
1475
1476 if (printDocAdapter_) {
1477 std::shared_ptr<PrintWriteResultCallbackAdapter> callback =
1478 std::make_shared<WebPrintWriteResultCallbackAdapter>(writeResultCallback);
1479 printDocAdapter_->OnStartLayoutWrite(jobId, oldAttrs, newAttrs, fd, callback);
1480 }
1481 }
1482
OnJobStateChanged(const std::string & jobId,uint32_t state)1483 void WebPrintDocument::OnJobStateChanged(const std::string& jobId, uint32_t state)
1484 {
1485 if (printDocAdapterV2_) {
1486 printDocAdapterV2_->OnJobStateChanged(jobId, state);
1487 return;
1488 }
1489
1490 if (printDocAdapter_) {
1491 printDocAdapter_->OnJobStateChanged(jobId, state);
1492 }
1493 }
1494
CreateWebPrintDocumentAdapter(const std::string & jobName,int32_t & useAdapterV2)1495 void* WebviewController::CreateWebPrintDocumentAdapter(
1496 const std::string& jobName, int32_t& useAdapterV2)
1497 {
1498 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1499 if (!nweb_ptr) {
1500 return nullptr;
1501 }
1502
1503 std::unique_ptr<NWebPrintDocumentAdapterAdapter> adapter =
1504 nweb_ptr->CreateWebPrintDocumentAdapterV2(jobName);
1505 if (adapter) {
1506 useAdapterV2 = 1;
1507 return adapter.release();
1508 }
1509
1510 useAdapterV2 = 0;
1511 return nweb_ptr->CreateWebPrintDocumentAdapter(jobName);
1512 }
1513
CloseAllMediaPresentations()1514 void WebviewController::CloseAllMediaPresentations()
1515 {
1516 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1517 if (nweb_ptr) {
1518 nweb_ptr->CloseAllMediaPresentations();
1519 }
1520 }
1521
StopAllMedia()1522 void WebviewController::StopAllMedia()
1523 {
1524 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1525 if (nweb_ptr) {
1526 nweb_ptr->StopAllMedia();
1527 }
1528 }
1529
ResumeAllMedia()1530 void WebviewController::ResumeAllMedia()
1531 {
1532 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1533 if (nweb_ptr) {
1534 nweb_ptr->ResumeAllMedia();
1535 }
1536 }
1537
PauseAllMedia()1538 void WebviewController::PauseAllMedia()
1539 {
1540 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1541 if (nweb_ptr) {
1542 nweb_ptr->PauseAllMedia();
1543 }
1544 }
1545
GetMediaPlaybackState()1546 int WebviewController::GetMediaPlaybackState()
1547 {
1548 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1549 if (!nweb_ptr) {
1550 return static_cast<int>(MediaPlaybackState::NONE);
1551 }
1552 return nweb_ptr->GetMediaPlaybackState();
1553 }
1554
GetSecurityLevel()1555 int WebviewController::GetSecurityLevel()
1556 {
1557 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1558 if (!nweb_ptr) {
1559 return static_cast<int>(SecurityLevel::NONE);
1560 }
1561
1562 int nwebSecurityLevel = nweb_ptr->GetSecurityLevel();
1563 SecurityLevel securityLevel;
1564 switch (nwebSecurityLevel) {
1565 case static_cast<int>(CoreSecurityLevel::NONE):
1566 securityLevel = SecurityLevel::NONE;
1567 break;
1568 case static_cast<int>(CoreSecurityLevel::SECURE):
1569 securityLevel = SecurityLevel::SECURE;
1570 break;
1571 case static_cast<int>(CoreSecurityLevel::WARNING):
1572 securityLevel = SecurityLevel::WARNING;
1573 break;
1574 case static_cast<int>(CoreSecurityLevel::DANGEROUS):
1575 securityLevel = SecurityLevel::DANGEROUS;
1576 break;
1577 default:
1578 securityLevel = SecurityLevel::NONE;
1579 break;
1580 }
1581
1582 return static_cast<int>(securityLevel);
1583 }
1584
IsIncognitoMode() const1585 bool WebviewController::IsIncognitoMode() const
1586 {
1587 bool incognitoMode = false;
1588 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1589 if (nweb_ptr) {
1590 incognitoMode = nweb_ptr->IsIncognitoMode();
1591 }
1592 return incognitoMode;
1593 }
1594
SetPrintBackground(bool enable)1595 void WebviewController::SetPrintBackground(bool enable)
1596 {
1597 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1598 if (nweb_ptr) {
1599 nweb_ptr->SetPrintBackground(enable);
1600 }
1601 }
1602
GetPrintBackground() const1603 bool WebviewController::GetPrintBackground() const
1604 {
1605 bool printBackgroundEnabled = false;
1606 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1607 if (nweb_ptr) {
1608 printBackgroundEnabled = nweb_ptr->GetPrintBackground();
1609 }
1610
1611 return printBackgroundEnabled;
1612 }
1613
EnableIntelligentTrackingPrevention(bool enable)1614 void WebviewController::EnableIntelligentTrackingPrevention(bool enable)
1615 {
1616 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1617 if (nweb_ptr) {
1618 nweb_ptr->EnableIntelligentTrackingPrevention(enable);
1619 }
1620 }
1621
IsIntelligentTrackingPreventionEnabled() const1622 bool WebviewController::IsIntelligentTrackingPreventionEnabled() const
1623 {
1624 bool enabled = false;
1625 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1626 if (nweb_ptr) {
1627 enabled = nweb_ptr->IsIntelligentTrackingPreventionEnabled();
1628 }
1629 return enabled;
1630 }
1631
WriteResultCallback(std::string jobId,uint32_t code)1632 void WebPrintWriteResultCallbackAdapter::WriteResultCallback(std::string jobId, uint32_t code)
1633 {
1634 if (cb_) {
1635 cb_(jobId, code);
1636 }
1637 }
1638
WriteResultCallback(const std::string & jobId,uint32_t code)1639 void WebPrintWriteResultCallbackAdapterV2::WriteResultCallback(const std::string& jobId, uint32_t code)
1640 {
1641 if (cb_) {
1642 cb_(jobId, code);
1643 }
1644 }
1645
SetWebSchemeHandler(const char * scheme,WebSchemeHandler * handler) const1646 bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const
1647 {
1648 if (!handler || !scheme) {
1649 WVLOG_E("WebviewController::SetWebSchemeHandler handler or scheme is nullptr");
1650 return false;
1651 }
1652 auto schemeHandler_ptr = WebSchemeHandler::GetArkWebSchemeHandler(handler);
1653 if (!schemeHandler_ptr) {
1654 WVLOG_E("WebviewController::SetWebSchemeHandler ArkWebSchemeHandler is nullptr");
1655 return false;
1656 }
1657 ArkWeb_SchemeHandler* schemeHandler =
1658 const_cast<ArkWeb_SchemeHandler*>(schemeHandler_ptr);
1659 return OH_ArkWeb_SetSchemeHandler(scheme, webTag_.c_str(), schemeHandler);
1660 }
1661
ClearWebSchemeHandler()1662 int32_t WebviewController::ClearWebSchemeHandler()
1663 {
1664 DeleteWebSchemeHandler();
1665 return OH_ArkWeb_ClearSchemeHandlers(webTag_.c_str());
1666 }
1667
SetWebServiveWorkerSchemeHandler(const char * scheme,WebSchemeHandler * handler)1668 bool WebviewController::SetWebServiveWorkerSchemeHandler(
1669 const char* scheme, WebSchemeHandler* handler)
1670 {
1671 auto schemeHandler_ptr = WebSchemeHandler::GetArkWebSchemeHandler(handler);
1672 if (!schemeHandler_ptr) {
1673 WVLOG_E("WebviewController::SetWebServiveWorkerSchemeHandler ArkWebSchemeHandler is nullptr");
1674 return false;
1675 }
1676 ArkWeb_SchemeHandler* schemeHandler =
1677 const_cast<ArkWeb_SchemeHandler*>(schemeHandler_ptr);
1678 return OH_ArkWebServiceWorker_SetSchemeHandler(scheme, schemeHandler);
1679 }
1680
ClearWebServiceWorkerSchemeHandler()1681 int32_t WebviewController::ClearWebServiceWorkerSchemeHandler()
1682 {
1683 DeleteWebServiceWorkerSchemeHandler();
1684 return OH_ArkWebServiceWorker_ClearSchemeHandlers();
1685 }
1686
StartCamera()1687 ErrCode WebviewController::StartCamera()
1688 {
1689 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1690 if (!nweb_ptr) {
1691 return NWebError::INIT_ERROR;
1692 }
1693
1694 nweb_ptr->StartCamera();
1695 return NWebError::NO_ERROR;
1696 }
1697
StopCamera()1698 ErrCode WebviewController::StopCamera()
1699 {
1700 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1701 if (!nweb_ptr) {
1702 return NWebError::INIT_ERROR;
1703 }
1704
1705 nweb_ptr->StopCamera();
1706 return NWebError::NO_ERROR;
1707 }
1708
CloseCamera()1709 ErrCode WebviewController::CloseCamera()
1710 {
1711 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1712 if (!nweb_ptr) {
1713 return NWebError::INIT_ERROR;
1714 }
1715
1716 nweb_ptr->CloseCamera();
1717 return NWebError::NO_ERROR;
1718 }
1719
GetLastJavascriptProxyCallingFrameUrl()1720 std::string WebviewController::GetLastJavascriptProxyCallingFrameUrl()
1721 {
1722 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1723 if (!nweb_ptr) {
1724 return "";
1725 }
1726
1727 return nweb_ptr->GetLastJavascriptProxyCallingFrameUrl();
1728 }
1729
OnCreateNativeMediaPlayer(napi_env env,napi_ref callback)1730 void WebviewController::OnCreateNativeMediaPlayer(napi_env env, napi_ref callback)
1731 {
1732 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1733 if (!nweb_ptr) {
1734 return;
1735 }
1736
1737 auto callbackImpl = std::make_shared<NWebCreateNativeMediaPlayerCallbackImpl>(nwebId_, env, callback);
1738 nweb_ptr->OnCreateNativeMediaPlayer(callbackImpl);
1739 }
1740
ParseScriptContent(napi_env env,napi_value value,std::string & script)1741 bool WebviewController::ParseScriptContent(napi_env env, napi_value value, std::string &script)
1742 {
1743 napi_valuetype valueType;
1744 napi_typeof(env, value, &valueType);
1745 if (valueType == napi_string) {
1746 std::string str;
1747 if (!NapiParseUtils::ParseString(env, value, str)) {
1748 WVLOG_E("PrecompileJavaScript: parse script text to string failed.");
1749 return false;
1750 }
1751
1752 script = str;
1753 return true;
1754 }
1755
1756 std::vector<uint8_t> vec = ParseUint8Array(env, value);
1757 if (!vec.size()) {
1758 WVLOG_E("PrecompileJavaScript: parse script text to Uint8Array failed.");
1759 return false;
1760 }
1761
1762 std::string str(vec.begin(), vec.end());
1763 script = str;
1764 return true;
1765 }
1766
ParseCacheOptions(napi_env env,napi_value value)1767 std::shared_ptr<CacheOptions> WebviewController::ParseCacheOptions(napi_env env, napi_value value) {
1768 std::map<std::string, std::string> responseHeaders;
1769 auto defaultCacheOptions = std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1770
1771 napi_value responseHeadersValue = nullptr;
1772 if (napi_get_named_property(env, value, "responseHeaders", &responseHeadersValue) != napi_ok) {
1773 WVLOG_D("PrecompileJavaScript: cannot get 'responseHeaders' of CacheOptions.");
1774 return defaultCacheOptions;
1775 }
1776
1777 if (!ParseResponseHeaders(env, responseHeadersValue, responseHeaders)) {
1778 WVLOG_D("PrecompileJavaScript: parse 'responseHeaders' of CacheOptions failed. use default options");
1779 return defaultCacheOptions;
1780 }
1781
1782 return std::make_shared<NWebCacheOptionsImpl>(responseHeaders);
1783 }
1784
PrecompileJavaScriptPromise(napi_env env,napi_deferred deferred,const std::string & url,const std::string & script,std::shared_ptr<CacheOptions> cacheOptions)1785 void WebviewController::PrecompileJavaScriptPromise(
1786 napi_env env, napi_deferred deferred,
1787 const std::string &url, const std::string &script, std::shared_ptr<CacheOptions> cacheOptions)
1788 {
1789 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1790 if (!nweb_ptr || !deferred) {
1791 return;
1792 }
1793
1794 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebPrecompileCallback>();
1795 callbackImpl->SetCallback([env, deferred](int64_t result) {
1796 if (!env) {
1797 return;
1798 }
1799
1800 NApiScope scope(env);
1801 if (!scope.IsVaild()) {
1802 return;
1803 }
1804
1805 napi_value setResult[RESULT_COUNT] = {0};
1806 napi_create_int64(env, result, &setResult[PARAMZERO]);
1807 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO]};
1808 if (result == static_cast<int64_t>(PrecompileError::OK)) {
1809 napi_resolve_deferred(env, deferred, args[PARAMZERO]);
1810 } else {
1811 napi_reject_deferred(env, deferred, args[PARAMZERO]);
1812 }
1813 });
1814
1815 nweb_ptr->PrecompileJavaScript(url, script, cacheOptions, callbackImpl);
1816 }
1817
ParseResponseHeaders(napi_env env,napi_value value,std::map<std::string,std::string> & responseHeaders) const1818 bool WebviewController::ParseResponseHeaders(napi_env env,
1819 napi_value value,
1820 std::map<std::string, std::string> &responseHeaders) const
1821 {
1822 bool isArray = false;
1823 napi_is_array(env, value, &isArray);
1824 if (!isArray) {
1825 WVLOG_E("Response headers is not array.");
1826 return false;
1827 }
1828
1829 uint32_t length = INTEGER_ZERO;
1830 napi_get_array_length(env, value, &length);
1831 for (uint32_t i = 0; i < length; i++) {
1832 std::string keyString;
1833 std::string valueString;
1834 napi_value header = nullptr;
1835 napi_value keyObj = nullptr;
1836 napi_value valueObj = nullptr;
1837 napi_get_element(env, value, i, &header);
1838
1839 if (napi_get_named_property(env, header, "headerKey", &keyObj) != napi_ok ||
1840 !NapiParseUtils::ParseString(env, keyObj, keyString)) {
1841 continue;
1842 }
1843
1844 if (napi_get_named_property(env, header, "headerValue", &valueObj) != napi_ok ||
1845 !NapiParseUtils::ParseString(env, valueObj, valueString)) {
1846 continue;
1847 }
1848
1849 responseHeaders[keyString] = valueString;
1850 }
1851
1852 return true;
1853 }
1854
ParseURLList(napi_env env,napi_value value,std::vector<std::string> & urlList)1855 ParseURLResult WebviewController::ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList)
1856 {
1857 if (!NapiParseUtils::ParseStringArray(env, value, urlList)) {
1858 return ParseURLResult::FAILED;
1859 }
1860
1861 for (auto url : urlList) {
1862 if (!CheckURL(url)) {
1863 return ParseURLResult::INVALID_URL;
1864 }
1865 }
1866
1867 return ParseURLResult::OK;
1868 }
1869
CheckURL(std::string & url) const1870 bool WebviewController::CheckURL(std::string& url) const
1871 {
1872 if (url.size() > URL_MAXIMUM) {
1873 WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{private}s", URL_MAXIMUM, url.c_str());
1874 return false;
1875 }
1876
1877 if (!regex_match(url, std::regex("^http(s)?:\\/\\/.+", std::regex_constants::icase))) {
1878 WVLOG_E("The Parse URL error. URL: %{private}s", url.c_str());
1879 return false;
1880 }
1881
1882 return true;
1883 }
1884
ParseUint8Array(napi_env env,napi_value value)1885 std::vector<uint8_t> WebviewController::ParseUint8Array(napi_env env, napi_value value)
1886 {
1887 napi_typedarray_type typedArrayType;
1888 size_t length = 0;
1889 napi_value buffer = nullptr;
1890 size_t offset = 0;
1891 napi_get_typedarray_info(env, value, &typedArrayType, &length, nullptr, &buffer, &offset);
1892 if (typedArrayType != napi_uint8_array) {
1893 WVLOG_E("Param is not Unit8Array.");
1894 return std::vector<uint8_t>();
1895 }
1896
1897 uint8_t *data = nullptr;
1898 size_t total = 0;
1899 napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total);
1900 length = std::min<size_t>(length, total - offset);
1901 std::vector<uint8_t> vec(length);
1902 int retCode = memcpy_s(vec.data(), vec.size(), &data[offset], length);
1903 if (retCode != 0) {
1904 WVLOG_E("Parse Uint8Array failed.");
1905 return std::vector<uint8_t>();
1906 }
1907
1908 return vec;
1909 }
1910
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)1911 void WebviewController::InjectOfflineResource(const std::vector<std::string>& urlList,
1912 const std::vector<uint8_t>& resource,
1913 const std::map<std::string, std::string>& response_headers,
1914 const uint32_t type)
1915 {
1916 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1917 if (!nweb_ptr) {
1918 return;
1919 }
1920
1921 std::string originUrl = urlList[0];
1922 if (urlList.size() == 1) {
1923 nweb_ptr->InjectOfflineResource(originUrl, originUrl, resource, response_headers, type);
1924 return;
1925 }
1926
1927 for (size_t i = 1 ; i < urlList.size() ; i++) {
1928 nweb_ptr->InjectOfflineResource(urlList[i], originUrl, resource, response_headers, type);
1929 }
1930 }
1931
EnableAdsBlock(bool enable)1932 void WebviewController::EnableAdsBlock(bool enable)
1933 {
1934 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1935 if (nweb_ptr) {
1936 nweb_ptr->EnableAdsBlock(enable);
1937 }
1938 }
1939
IsAdsBlockEnabled() const1940 bool WebviewController::IsAdsBlockEnabled() const
1941 {
1942 bool enabled = false;
1943 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1944 if (nweb_ptr) {
1945 enabled = nweb_ptr->IsAdsBlockEnabled();
1946 }
1947 return enabled;
1948 }
1949
IsAdsBlockEnabledForCurPage() const1950 bool WebviewController::IsAdsBlockEnabledForCurPage() const
1951 {
1952 bool enabled = false;
1953 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1954 if (nweb_ptr) {
1955 enabled = nweb_ptr->IsAdsBlockEnabledForCurPage();
1956 }
1957 return enabled;
1958 }
1959
GetSurfaceId()1960 std::string WebviewController::GetSurfaceId()
1961 {
1962 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1963 if (!nweb_ptr) {
1964 return "";
1965 }
1966 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1967 if (!setting) {
1968 return "";
1969 }
1970 return setting->GetSurfaceId();
1971 }
1972
UpdateInstanceId(int32_t newId)1973 void WebviewController::UpdateInstanceId(int32_t newId)
1974 {
1975 if (javaScriptResultCb_) {
1976 javaScriptResultCb_->UpdateInstanceId(newId);
1977 }
1978 }
1979
SetUrlTrustList(const std::string & urlTrustList,std::string & detailErrMsg)1980 ErrCode WebviewController::SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg)
1981 {
1982 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1983 if (!nweb_ptr) {
1984 return NWebError::INIT_ERROR;
1985 }
1986
1987 int ret = NWebError::NO_ERROR;
1988 switch (nweb_ptr->SetUrlTrustListWithErrMsg(urlTrustList, detailErrMsg)) {
1989 case static_cast<int>(UrlListSetResult::INIT_ERROR):
1990 ret = NWebError::INIT_ERROR;
1991 break;
1992 case static_cast<int>(UrlListSetResult::PARAM_ERROR):
1993 ret = NWebError::PARAM_CHECK_ERROR;
1994 break;
1995 case static_cast<int>(UrlListSetResult::SET_OK):
1996 ret = NWebError::NO_ERROR;
1997 break;
1998 default:
1999 ret = NWebError::PARAM_CHECK_ERROR;
2000 break;
2001 }
2002 return ret;
2003 }
ParseJsLengthResourceToInt(napi_env env,napi_value jsLength,PixelUnit & type,int32_t & result) const2004 bool WebviewController::ParseJsLengthResourceToInt(
2005 napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const
2006 {
2007 napi_value resIdObj = nullptr;
2008 int32_t resId;
2009
2010 if ((napi_get_named_property(env, jsLength, "id", &resIdObj) != napi_ok)) {
2011 return false;
2012 }
2013
2014 if (!NapiParseUtils::ParseInt32(env, resIdObj, resId)) {
2015 return false;
2016 }
2017
2018 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
2019 AbilityRuntime::ApplicationContext::GetApplicationContext();
2020 if (!context) {
2021 WVLOG_E("WebPageSnapshot Failed to get application context.");
2022 return false;
2023 }
2024 auto resourceManager = context->GetResourceManager();
2025 if (!resourceManager) {
2026 WVLOG_E("WebPageSnapshot Failed to get resource manager.");
2027 return false;
2028 }
2029
2030 napi_value jsResourceType = nullptr;
2031 napi_valuetype resourceType = napi_null;
2032 napi_get_named_property(env, jsLength, "type", &jsResourceType);
2033 napi_typeof(env, jsResourceType, &resourceType);
2034 if (resourceType == napi_number) {
2035 int32_t resourceTypeNum;
2036 NapiParseUtils::ParseInt32(env, jsResourceType, resourceTypeNum);
2037 std::string resourceString;
2038 switch (resourceTypeNum) {
2039 case static_cast<int>(ResourceType::INTEGER):
2040 if (resourceManager->GetIntegerById(resId, result) == Global::Resource::SUCCESS) {
2041 type = PixelUnit::VP;
2042 return true;
2043 }
2044 break;
2045 case static_cast<int>(ResourceType::STRING):
2046 if (resourceManager->GetStringById(resId, resourceString) == Global::Resource::SUCCESS) {
2047 return NapiParseUtils::ParseJsLengthStringToInt(resourceString, type, result);
2048 }
2049 break;
2050 default:
2051 WVLOG_E("WebPageSnapshot resource type not support");
2052 break;
2053 }
2054 return false;
2055 }
2056 WVLOG_E("WebPageSnapshot resource type error");
2057 return false;
2058 }
2059
ParseJsLengthToInt(napi_env env,napi_value jsLength,PixelUnit & type,int32_t & result) const2060 bool WebviewController::ParseJsLengthToInt(
2061 napi_env env, napi_value jsLength, PixelUnit &type, int32_t &result) const
2062 {
2063 napi_valuetype jsType = napi_null;
2064 napi_typeof(env, jsLength, &jsType);
2065 if ((jsType != napi_object) && (jsType != napi_string) && (jsType != napi_number)) {
2066 WVLOG_E("WebPageSnapshot Unable to parse js length object.");
2067 return false;
2068 }
2069
2070 if (jsType == napi_number) {
2071 NapiParseUtils::ParseInt32(env, jsLength, result);
2072 type = PixelUnit::VP;
2073 return true;
2074 }
2075
2076 if (jsType == napi_string) {
2077 std::string nativeString;
2078 NapiParseUtils::ParseString(env, jsLength, nativeString);
2079 if (!NapiParseUtils::ParseJsLengthStringToInt(nativeString, type, result)) {
2080 return false;
2081 }
2082 return true;
2083 }
2084
2085 if (jsType == napi_object) {
2086 return ParseJsLengthResourceToInt(env, jsLength, type, result);
2087 }
2088 return false;
2089 }
2090
WebPageSnapshot(const char * id,PixelUnit type,int32_t width,int32_t height,const WebSnapshotCallback callback)2091 ErrCode WebviewController::WebPageSnapshot(
2092 const char *id, PixelUnit type, int32_t width, int32_t height, const WebSnapshotCallback callback)
2093 {
2094 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2095 if (!nweb_ptr) {
2096 return INIT_ERROR;
2097 }
2098
2099 bool init = nweb_ptr->WebPageSnapshot(id, type, width, height, std::move(callback));
2100 if (!init) {
2101 return INIT_ERROR;
2102 }
2103
2104 return NWebError::NO_ERROR;
2105 }
2106
GetHapModuleInfo()2107 bool WebviewController::GetHapModuleInfo()
2108 {
2109 sptr<ISystemAbilityManager> systemAbilityManager =
2110 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2111 if (systemAbilityManager == nullptr) {
2112 WVLOG_E("get SystemAbilityManager failed");
2113 return false;
2114 }
2115 sptr<IRemoteObject> remoteObject =
2116 systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2117 if (remoteObject == nullptr) {
2118 WVLOG_E("get Bundle Manager failed");
2119 return false;
2120 }
2121 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
2122 if (bundleMgr == nullptr) {
2123 WVLOG_E("get Bundle Manager failed");
2124 return false;
2125 }
2126 AppExecFwk::BundleInfo bundleInfo;
2127 if (bundleMgr->GetBundleInfoForSelf(
2128 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
2129 bundleInfo) != 0) {
2130 WVLOG_E("get bundle info failed");
2131 return false;
2132 }
2133 moduleName_ = bundleInfo.moduleNames;
2134 return true;
2135 }
2136
SetPathAllowingUniversalAccess(const std::vector<std::string> & pathList,std::string & errorPath)2137 void WebviewController::SetPathAllowingUniversalAccess(
2138 const std::vector<std::string>& pathList, std::string& errorPath)
2139 {
2140 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2141 if (!nweb_ptr) {
2142 return;
2143 }
2144 if (moduleName_.empty()) {
2145 WVLOG_I("need to get module name for path");
2146 if (!GetHapModuleInfo()) {
2147 WVLOG_E("GetHapModuleInfo failed");
2148 moduleName_.clear();
2149 return;
2150 }
2151 }
2152 nweb_ptr->SetPathAllowingUniversalAccess(pathList, moduleName_, errorPath);
2153 }
2154
ScrollToWithAnime(float x,float y,int32_t duration)2155 void WebviewController::ScrollToWithAnime(float x, float y, int32_t duration)
2156 {
2157 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2158 if (nweb_ptr) {
2159 nweb_ptr->ScrollToWithAnime(x, y, duration);
2160 }
2161 return;
2162 }
2163
ScrollByWithAnime(float deltaX,float deltaY,int32_t duration)2164 void WebviewController::ScrollByWithAnime(float deltaX, float deltaY, int32_t duration)
2165 {
2166 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2167 if (nweb_ptr) {
2168 nweb_ptr->ScrollByWithAnime(deltaX, deltaY, duration);
2169 }
2170 return;
2171 }
2172
SetBackForwardCacheOptions(int32_t size,int32_t timeToLive)2173 void WebviewController::SetBackForwardCacheOptions(int32_t size, int32_t timeToLive)
2174 {
2175 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2176 if (!nweb_ptr) {
2177 return;
2178 }
2179
2180 nweb_ptr->SetBackForwardCacheOptions(size, timeToLive);
2181 }
2182
GetScrollOffset(float * offset_x,float * offset_y)2183 void WebviewController::GetScrollOffset(float* offset_x, float* offset_y)
2184 {
2185 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2186 if (nweb_ptr) {
2187 nweb_ptr->GetScrollOffset(offset_x, offset_y);
2188 }
2189 }
2190
GetPageOffset(float * offset_x,float * offset_y)2191 void WebviewController::GetPageOffset(float* offset_x, float* offset_y)
2192 {
2193 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2194 if (nweb_ptr) {
2195 nweb_ptr->GetPageOffset(offset_x, offset_y);
2196 }
2197 }
2198
ScrollByWithResult(float deltaX,float deltaY) const2199 bool WebviewController::ScrollByWithResult(float deltaX, float deltaY) const
2200 {
2201 bool enabled = false;
2202 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2203 if (nweb_ptr) {
2204 enabled = nweb_ptr->ScrollByWithResult(deltaX, deltaY);
2205 }
2206 return enabled;
2207 }
2208
SetScrollable(bool enable,int32_t scrollType)2209 void WebviewController::SetScrollable(bool enable, int32_t scrollType)
2210 {
2211 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2212 if (!nweb_ptr) {
2213 return;
2214 }
2215 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
2216 if (!setting) {
2217 return;
2218 }
2219 return setting->SetScrollable(enable, scrollType);
2220 }
2221
SetType(int type)2222 void WebMessageExt::SetType(int type)
2223 {
2224 type_ = type;
2225 WebMessageType jsType = static_cast<WebMessageType>(type);
2226 NWebValue::Type nwebType = NWebValue::Type::NONE;
2227 NWebRomValue::Type romType = NWebRomValue::Type::NONE;
2228 switch (jsType) {
2229 case WebMessageType::STRING: {
2230 nwebType = NWebValue::Type::STRING;
2231 romType = NWebRomValue::Type::STRING;
2232 break;
2233 }
2234 case WebMessageType::NUMBER: {
2235 nwebType = NWebValue::Type::DOUBLE;
2236 romType = NWebRomValue::Type::DOUBLE;
2237 break;
2238 }
2239 case WebMessageType::BOOLEAN: {
2240 nwebType = NWebValue::Type::BOOLEAN;
2241 romType = NWebRomValue::Type::BOOLEAN;
2242 break;
2243 }
2244 case WebMessageType::ARRAYBUFFER: {
2245 nwebType = NWebValue::Type::BINARY;
2246 romType = NWebRomValue::Type::BINARY;
2247 break;
2248 }
2249 case WebMessageType::ARRAY: {
2250 nwebType = NWebValue::Type::STRINGARRAY;
2251 romType = NWebRomValue::Type::STRINGARRAY;
2252 break;
2253 }
2254 case WebMessageType::ERROR: {
2255 nwebType = NWebValue::Type::ERROR;
2256 romType = NWebRomValue::Type::ERROR;
2257 break;
2258 }
2259 default: {
2260 nwebType = NWebValue::Type::NONE;
2261 romType = NWebRomValue::Type::NONE;
2262 break;
2263 }
2264 }
2265 if (data_) {
2266 data_->SetType(nwebType);
2267 }
2268 if (value_) {
2269 value_->SetType(romType);
2270 }
2271 }
2272
ConvertNwebType2JsType(NWebValue::Type type)2273 int WebMessageExt::ConvertNwebType2JsType(NWebValue::Type type)
2274 {
2275 WebMessageType jsType = WebMessageType::NOTSUPPORT;
2276 switch (type) {
2277 case NWebValue::Type::STRING: {
2278 jsType = WebMessageType::STRING;
2279 break;
2280 }
2281 case NWebValue::Type::DOUBLE:
2282 case NWebValue::Type::INTEGER: {
2283 jsType = WebMessageType::NUMBER;
2284 break;
2285 }
2286 case NWebValue::Type::BOOLEAN: {
2287 jsType = WebMessageType::BOOLEAN;
2288 break;
2289 }
2290 case NWebValue::Type::STRINGARRAY:
2291 case NWebValue::Type::DOUBLEARRAY:
2292 case NWebValue::Type::INT64ARRAY:
2293 case NWebValue::Type::BOOLEANARRAY: {
2294 jsType = WebMessageType::ARRAY;
2295 break;
2296 }
2297 case NWebValue::Type::BINARY: {
2298 jsType = WebMessageType::ARRAYBUFFER;
2299 break;
2300 }
2301 case NWebValue::Type::ERROR: {
2302 jsType = WebMessageType::ERROR;
2303 break;
2304 }
2305 default: {
2306 jsType = WebMessageType::NOTSUPPORT;
2307 break;
2308 }
2309 }
2310 return static_cast<int>(jsType);
2311 }
2312
GetLastHitTest()2313 std::shared_ptr<HitTestResult> WebviewController::GetLastHitTest()
2314 {
2315 std::shared_ptr<HitTestResult> nwebResult;
2316 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2317 if (nweb_ptr) {
2318 nwebResult = nweb_ptr->GetLastHitTestResult();
2319 if (nwebResult) {
2320 nwebResult->SetType(ConverToWebHitTestType(nwebResult->GetType()));
2321 }
2322 }
2323 return nwebResult;
2324 }
2325
SaveWebSchemeHandler(const char * scheme,WebSchemeHandler * handler)2326 void WebviewController::SaveWebSchemeHandler(const char* scheme, WebSchemeHandler* handler)
2327 {
2328 auto iter = webSchemeHandlerMap_.find(scheme);
2329 if (iter != webSchemeHandlerMap_.end()) {
2330 return;
2331 }
2332 webSchemeHandlerMap_[scheme] = handler;
2333 }
2334
SaveWebServiceWorkerSchemeHandler(const char * scheme,WebSchemeHandler * handler)2335 void WebviewController::SaveWebServiceWorkerSchemeHandler(const char* scheme, WebSchemeHandler* handler)
2336 {
2337 auto iter = webServiceWorkerSchemeHandlerMap_.find(scheme);
2338 if (iter != webServiceWorkerSchemeHandlerMap_.end()) {
2339 return;
2340 }
2341 webServiceWorkerSchemeHandlerMap_[scheme] = handler;
2342 }
2343
DeleteWebSchemeHandler()2344 void WebviewController::DeleteWebSchemeHandler()
2345 {
2346 for (const auto &iter : webSchemeHandlerMap_) {
2347 iter.second->DeleteReference(iter.second);
2348 }
2349 webSchemeHandlerMap_.clear();
2350 }
2351
DeleteWebServiceWorkerSchemeHandler()2352 void WebviewController::DeleteWebServiceWorkerSchemeHandler()
2353 {
2354 for (const auto &iter : webServiceWorkerSchemeHandlerMap_) {
2355 iter.second->DeleteReference(iter.second);
2356 }
2357 webServiceWorkerSchemeHandlerMap_.clear();
2358 }
2359
GetAttachState()2360 int WebviewController::GetAttachState()
2361 {
2362 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2363 if (nweb_ptr) {
2364 return static_cast<int>(attachState_);
2365 }
2366 return static_cast<int>(AttachState::NOT_ATTACHED);
2367 }
2368
RegisterStateChangeCallback(const napi_env & env,const std::string & type,napi_value handler)2369 void WebviewController::RegisterStateChangeCallback(const napi_env& env, const std::string& type, napi_value handler)
2370 {
2371 napi_ref handlerRef = nullptr;
2372 napi_create_reference(env, handler, 1, &handlerRef);
2373 WebRegObj regObj(env, handlerRef);
2374 auto iter = attachEventRegisterInfo_.find(type);
2375 if (iter == attachEventRegisterInfo_.end()) {
2376 attachEventRegisterInfo_[type] = std::vector<WebRegObj> {regObj};
2377 WVLOG_I("WebviewController::RegisterStateChangeCallback add new type.");
2378 return;
2379 }
2380 bool found = false;
2381 for (auto& regObjInList : iter->second) {
2382 if (env == regObjInList.m_regEnv) {
2383 napi_value handlerTemp = nullptr;
2384 if (napi_get_reference_value(env, regObjInList.m_regHanderRef, &handlerTemp) != napi_ok) {
2385 WVLOG_E("WebviewController::RegisterStateChangeCallback Failed to get reference value.");
2386 napi_delete_reference(env, handlerRef);
2387 return;
2388 }
2389 bool isEqual = false;
2390 if (napi_strict_equals(env, handlerTemp, handler, &isEqual) != napi_ok) {
2391 WVLOG_E("WebviewController::RegisterStateChangeCallback Failed to compare handlers.");
2392 napi_delete_reference(env, handlerRef);
2393 return;
2394 }
2395 if (isEqual) {
2396 WVLOG_E("WebviewController::RegisterStateChangeCallback handler function is same");
2397 found = true;
2398 break;
2399 }
2400 }
2401 }
2402 if (!found) {
2403 iter->second.emplace_back(regObj);
2404 }
2405 }
2406
DeleteRegisterObj(const napi_env & env,std::vector<WebRegObj> & vecRegObjs,napi_value & handler)2407 void WebviewController::DeleteRegisterObj(const napi_env& env, std::vector<WebRegObj>& vecRegObjs, napi_value& handler)
2408 {
2409 auto iter = vecRegObjs.begin();
2410 while (iter != vecRegObjs.end()) {
2411 if (env == iter->m_regEnv && !iter->m_isMarked) {
2412 napi_value handlerTemp = nullptr;
2413 napi_status status = napi_get_reference_value(env, iter->m_regHanderRef, &handlerTemp);
2414 if (status != napi_ok) {
2415 WVLOG_E("WebviewController::DeleteRegisterObj Failed to get reference value.");
2416 ++iter;
2417 continue;
2418 }
2419 if (handlerTemp == nullptr) {
2420 WVLOG_W("WebviewController::DeleteRegisterObj handlerTemp is null");
2421 }
2422 if (handler == nullptr) {
2423 WVLOG_W("WebviewController::DeleteRegisterObj handler is null");
2424 }
2425 bool isEqual = false;
2426 status = napi_strict_equals(env, handlerTemp, handler, &isEqual);
2427 if (status != napi_ok) {
2428 WVLOG_E("WebviewController::DeleteRegisterObj Failed to compare handlers.");
2429 ++iter;
2430 continue;
2431 }
2432 WVLOG_D("WebviewController::DeleteRegisterObj Delete register isEqual = %{public}d", isEqual);
2433 if (isEqual) {
2434 iter->m_isMarked = true;
2435 WVLOG_I("WebviewController::DeleteRegisterObj Delete register object ref.");
2436 break;
2437 } else {
2438 ++iter;
2439 }
2440 } else {
2441 WVLOG_D(
2442 "WebviewController::DeleteRegisterObj Unregister event, env is not equal %{private}p, : %{private}p",
2443 env, iter->m_regEnv);
2444 ++iter;
2445 }
2446 }
2447 }
2448
DeleteAllRegisterObj(const napi_env & env,std::vector<WebRegObj> & vecRegObjs)2449 void WebviewController::DeleteAllRegisterObj(const napi_env& env, std::vector<WebRegObj>& vecRegObjs)
2450 {
2451 auto iter = vecRegObjs.begin();
2452 for (; iter != vecRegObjs.end();) {
2453 if (env == iter->m_regEnv && !iter->m_isMarked) {
2454 iter->m_isMarked = true;
2455 } else {
2456 WVLOG_D("WebviewController::DeleteAllRegisterObj Unregister all event, env is not equal %{private}p, : "
2457 "%{private}p",
2458 env, iter->m_regEnv);
2459 ++iter;
2460 }
2461 }
2462 }
2463
UnregisterStateChangeCallback(const napi_env & env,const std::string & type,napi_value handler)2464 void WebviewController::UnregisterStateChangeCallback(const napi_env& env, const std::string& type, napi_value handler)
2465 {
2466 auto iter = attachEventRegisterInfo_.find(type);
2467 if (iter == attachEventRegisterInfo_.end()) {
2468 WVLOG_W("WebviewController::UnregisterStateChangeCallback Unregister type not registered!");
2469 return;
2470 }
2471 if (handler != nullptr) {
2472 DeleteRegisterObj(env, iter->second, handler);
2473 } else {
2474 WVLOG_I("WebviewController::UnregisterStateChangeCallback All callback is unsubscribe for event: %{public}s",
2475 type.c_str());
2476 DeleteAllRegisterObj(env, iter->second);
2477 }
2478 if (iter->second.empty()) {
2479 attachEventRegisterInfo_.erase(iter);
2480 }
2481 }
2482
WaitForAttached(napi_env env,void * data)2483 void WebviewController::WaitForAttached(napi_env env, void* data)
2484 {
2485 WVLOG_D("WebviewController::WaitForAttached start");
2486 WaitForAttachParam* param = static_cast<WaitForAttachParam*>(data);
2487 std::unique_lock<std::mutex> attachLock(param->webviewController->attachMtx_);
2488 param->webviewController->attachCond_.wait_for(attachLock, std::chrono::milliseconds(param->timeout), [param] {
2489 return param->webviewController->attachState_ == AttachState::ATTACHED;
2490 });
2491 param->state = static_cast<int32_t>(param->webviewController->attachState_);
2492 }
2493
TriggerWaitforAttachedPromise(napi_env env,napi_status status,void * data)2494 void WebviewController::TriggerWaitforAttachedPromise(napi_env env, napi_status status, void* data)
2495 {
2496 WaitForAttachParam* param = static_cast<WaitForAttachParam*>(data);
2497 napi_handle_scope scope = nullptr;
2498 napi_open_handle_scope(env, &scope);
2499 if (scope == nullptr) {
2500 delete param;
2501 param = nullptr;
2502 return;
2503 }
2504
2505 WVLOG_D("WebviewController::TriggerWaitforAttachedPromise start");
2506 if (param->deferred != nullptr) {
2507 napi_value jsState = nullptr;
2508 napi_create_int32(env, param->state, &jsState);
2509 napi_resolve_deferred(env, param->deferred, jsState);
2510 }
2511 napi_close_handle_scope(env, scope);
2512 napi_delete_async_work(env, param->asyncWork);
2513 delete param;
2514 param = nullptr;
2515 }
2516
WaitForAttachedPromise(napi_env env,int32_t timeout,napi_deferred deferred)2517 napi_value WebviewController::WaitForAttachedPromise(napi_env env, int32_t timeout, napi_deferred deferred)
2518 {
2519 napi_value result = nullptr;
2520 napi_value resourceName = nullptr;
2521 WaitForAttachParam *param = new (std::nothrow) WaitForAttachParam {
2522 .asyncWork = nullptr,
2523 .deferred = deferred,
2524 .timeout = timeout,
2525 .webviewController = this,
2526 .state = static_cast<int32_t>(attachState_),
2527 };
2528 if (param == nullptr) {
2529 return nullptr;
2530 }
2531
2532 NAPI_CALL(env, napi_create_string_utf8(env, EVENT_WAIT_FOR_ATTACH.c_str(), NAPI_AUTO_LENGTH, &resourceName));
2533 NAPI_CALL(env, napi_create_async_work(env, nullptr, resourceName, WaitForAttached,
2534 TriggerWaitforAttachedPromise, static_cast<void *>(param), ¶m->asyncWork));
2535 NAPI_CALL(env, napi_queue_async_work_with_qos(env, param->asyncWork, napi_qos_user_initiated));
2536 napi_get_undefined(env, &result);
2537 return result;
2538 }
2539
GetBlanklessInfoWithKey(const std::string & key,double * similarity,int32_t * loadingTime)2540 int32_t WebviewController::GetBlanklessInfoWithKey(const std::string& key, double* similarity, int32_t* loadingTime)
2541 {
2542 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2543 if (nweb_ptr) {
2544 return nweb_ptr->GetBlanklessInfoWithKey(key, similarity, loadingTime);
2545 }
2546 return -1;
2547 }
2548
SetBlanklessLoadingWithKey(const std::string & key,bool isStart)2549 int32_t WebviewController::SetBlanklessLoadingWithKey(const std::string& key, bool isStart)
2550 {
2551 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2552 if (nweb_ptr) {
2553 return nweb_ptr->SetBlanklessLoadingWithKey(key, isStart);
2554 }
2555 return -1;
2556 }
2557
AvoidVisibleViewportBottom(int32_t avoidHeight)2558 ErrCode WebviewController::AvoidVisibleViewportBottom(int32_t avoidHeight)
2559 {
2560 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2561 if (!nweb_ptr) {
2562 return INIT_ERROR;
2563 }
2564 nweb_ptr->AvoidVisibleViewportBottom(avoidHeight);
2565 return NWebError::NO_ERROR;
2566 }
2567
SetErrorPageEnabled(bool enable)2568 ErrCode WebviewController::SetErrorPageEnabled(bool enable)
2569 {
2570 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2571 if (!nweb_ptr) {
2572 return INIT_ERROR;
2573 }
2574 nweb_ptr->SetErrorPageEnabled(enable);
2575 return NWebError::NO_ERROR;
2576 }
2577
GetErrorPageEnabled()2578 bool WebviewController::GetErrorPageEnabled()
2579 {
2580 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
2581 if (!nweb_ptr) {
2582 return false;
2583 }
2584 return nweb_ptr->GetErrorPageEnabled();
2585 }
2586 } // namespace NWeb
2587 } // namespace OHOS
2588