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