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 #include <memory>
18 #include <unordered_map>
19
20 #include "application_context.h"
21 #include "business_error.h"
22 #include "napi_parse_utils.h"
23
24 #include "native_arkweb_utils.h"
25 #include "native_interface_arkweb.h"
26
27 #include "nweb_log.h"
28 #include "nweb_store_web_archive_callback.h"
29 #include "web_errors.h"
30 #include "webview_hasimage_callback.h"
31 #include "webview_javascript_execute_callback.h"
32 #include "webview_javascript_result_callback.h"
33
34 namespace {
35 constexpr int32_t PARAMZERO = 0;
36 constexpr int32_t PARAMONE = 1;
37 constexpr int32_t RESULT_COUNT = 2;
38 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
39 const std::string MODULE_NAME_PREFIX = "moduleName:";
40 } // namespace
41
42 namespace OHOS {
43 namespace NWeb {
44 namespace {
GetAppBundleNameAndModuleName(std::string & bundleName,std::string & moduleName)45 bool GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleName)
46 {
47 static std::string applicationBundleName;
48 static std::string applicationModuleName;
49 if (!applicationBundleName.empty() && !applicationModuleName.empty()) {
50 bundleName = applicationBundleName;
51 moduleName = applicationModuleName;
52 return true;
53 }
54 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
55 AbilityRuntime::ApplicationContext::GetApplicationContext();
56 if (!context) {
57 WVLOG_E("Failed to get application context.");
58 return false;
59 }
60 auto resourceManager = context->GetResourceManager();
61 if (!resourceManager) {
62 WVLOG_E("Failed to get resource manager.");
63 return false;
64 }
65 applicationBundleName = resourceManager->bundleInfo.first;
66 applicationModuleName = resourceManager->bundleInfo.second;
67 bundleName = applicationBundleName;
68 moduleName = applicationModuleName;
69 WVLOG_D("application bundleName: %{public}s, moduleName: %{public}s", bundleName.c_str(), moduleName.c_str());
70 return true;
71 }
72 }
73 using namespace NWebError;
74 std::unordered_map<int32_t, WebviewController*> g_webview_controller_map;
75 std::string WebviewController::customeSchemeCmdLine_ = "";
76 bool WebviewController::existNweb_ = false;
77 bool WebviewController::webDebuggingAccess_ = false;
78
WebviewController(int32_t nwebId)79 WebviewController::WebviewController(int32_t nwebId) : nweb_(NWebHelper::Instance().GetNWeb(nwebId)), id_(nwebId)
80 {
81 if (IsInit()) {
82 std::unique_lock<std::mutex> lk(webMtx_);
83 g_webview_controller_map.emplace(nwebId, this);
84 }
85 }
86
~WebviewController()87 WebviewController::~WebviewController()
88 {
89 std::unique_lock<std::mutex> lk(webMtx_);
90 g_webview_controller_map.erase(id_);
91 }
92
SetWebId(int32_t nwebId)93 void WebviewController::SetWebId(int32_t nwebId)
94 {
95 id_ = nwebId;
96 nweb_ = NWebHelper::Instance().GetNWeb(nwebId);
97 std::unique_lock<std::mutex> lk(webMtx_);
98 g_webview_controller_map.emplace(nwebId, this);
99
100 if (webTag_.empty()) {
101 WVLOG_I("native webtag is empty, don't care because it's not a native instance");
102 return;
103 }
104 if (auto nweb = nweb_.lock()) {
105 OH_NativeArkWeb_BindWebTagToWebInstance(webTag_.c_str(), nweb_);
106 NWebHelper::Instance().SetWebTag(id_, webTag_.c_str());
107 }
108 SetNWebJavaScriptResultCallBack();
109 NativeArkWeb_OnValidCallback validCallback = OH_NativeArkWeb_GetJavaScriptProxyValidCallback(webTag_.c_str());
110 if (validCallback) {
111 WVLOG_I("native validCallback start to call");
112 (*validCallback)(webTag_.c_str());
113 } else {
114 WVLOG_W("native validCallback is null, callback nothing");
115 }
116 }
117
FromID(int32_t nwebId)118 WebviewController* WebviewController::FromID(int32_t nwebId)
119 {
120 std::unique_lock<std::mutex> lk(webMtx_);
121 if (auto it = g_webview_controller_map.find(nwebId); it != g_webview_controller_map.end()) {
122 auto control = it->second;
123 return control;
124 }
125 return nullptr;
126 }
127
InnerCompleteWindowNew(int32_t parentNwebId)128 void WebviewController::InnerCompleteWindowNew(int32_t parentNwebId)
129 {
130 WVLOG_D("WebviewController::InnerCompleteWindowNew parentNwebId == "
131 "%{public}d ",
132 parentNwebId);
133 if (parentNwebId < 0) {
134 WVLOG_E("WebviewController::InnerCompleteWindowNew parentNwebId == %{public}d "
135 "error",
136 parentNwebId);
137 return;
138 }
139 auto parentControl = FromID(parentNwebId);
140 if (!parentControl || !(parentControl->javaScriptResultCb_)) {
141 WVLOG_E("WebviewController::InnerCompleteWindowNew parentControl or "
142 "javaScriptResultCb_ is null");
143 return;
144 }
145 auto objs = parentControl->javaScriptResultCb_->GetNamedObjects();
146 SetNWebJavaScriptResultCallBack();
147 for (auto it = objs.begin(); it != objs.end(); it++) {
148 if (it->second && IsInit()) {
149 RegisterJavaScriptProxy(
150 it->second->GetEnv(), it->second->GetValue(), it->first, it->second->GetMethodNames());
151 }
152 }
153 }
154
IsInit()155 bool WebviewController::IsInit()
156 {
157 return nweb_.lock() ? true : false;
158 }
159
AccessForward()160 bool WebviewController::AccessForward()
161 {
162 bool access = false;
163 auto nweb_ptr = nweb_.lock();
164 if (nweb_ptr) {
165 access = nweb_ptr->IsNavigateForwardAllowed();
166 }
167 return access;
168 }
169
AccessBackward()170 bool WebviewController::AccessBackward()
171 {
172 bool access = false;
173 auto nweb_ptr = nweb_.lock();
174 if (nweb_ptr) {
175 access = nweb_ptr->IsNavigatebackwardAllowed();
176 }
177 return access;
178 }
179
AccessStep(int32_t step)180 bool WebviewController::AccessStep(int32_t step)
181 {
182 bool access = false;
183 auto nweb_ptr = nweb_.lock();
184 if (nweb_ptr) {
185 access = nweb_ptr->CanNavigateBackOrForward(step);
186 }
187 return access;
188 }
189
ClearHistory()190 void WebviewController::ClearHistory()
191 {
192 auto nweb_ptr = nweb_.lock();
193 if (nweb_ptr) {
194 nweb_ptr->DeleteNavigateHistory();
195 }
196 }
197
Forward()198 void WebviewController::Forward()
199 {
200 auto nweb_ptr = nweb_.lock();
201 if (nweb_ptr) {
202 nweb_ptr->NavigateForward();
203 }
204 }
205
Backward()206 void WebviewController::Backward()
207 {
208 auto nweb_ptr = nweb_.lock();
209 if (nweb_ptr) {
210 nweb_ptr->NavigateBack();
211 }
212 }
213
OnActive()214 void WebviewController::OnActive()
215 {
216 auto nweb_ptr = nweb_.lock();
217 if (nweb_ptr) {
218 nweb_ptr->OnContinue();
219 }
220 }
221
OnInactive()222 void WebviewController::OnInactive()
223 {
224 auto nweb_ptr = nweb_.lock();
225 if (nweb_ptr) {
226 nweb_ptr->OnPause();
227 }
228 }
229
Refresh()230 void WebviewController::Refresh()
231 {
232 auto nweb_ptr = nweb_.lock();
233 if (nweb_ptr) {
234 nweb_ptr->Reload();
235 }
236 }
237
ZoomIn()238 ErrCode WebviewController::ZoomIn()
239 {
240 auto nweb_ptr = nweb_.lock();
241 if (!nweb_ptr) {
242 return INIT_ERROR;
243 }
244 ErrCode result = NWebError::NO_ERROR;
245 result = nweb_ptr->ZoomIn();
246
247 return result;
248 }
249
ZoomOut()250 ErrCode WebviewController::ZoomOut()
251 {
252 auto nweb_ptr = nweb_.lock();
253 if (!nweb_ptr) {
254 return INIT_ERROR;
255 }
256 ErrCode result = NWebError::NO_ERROR;
257 result = nweb_ptr->ZoomOut();
258
259 return result;
260 }
261
GetWebId() const262 int32_t WebviewController::GetWebId() const
263 {
264 int32_t webId = -1;
265 auto nweb_ptr = nweb_.lock();
266 if (nweb_ptr) {
267 webId = static_cast<int32_t>(nweb_ptr->GetWebId());
268 }
269 return webId;
270 }
271
GetUserAgent()272 std::string WebviewController::GetUserAgent()
273 {
274 auto nweb_ptr = nweb_.lock();
275 if (!nweb_ptr) {
276 return "";
277 }
278 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
279 if (!setting) {
280 return "";
281 }
282 return setting->DefaultUserAgent();
283 }
284
GetCustomUserAgent() const285 std::string WebviewController::GetCustomUserAgent() const
286 {
287 auto nweb_ptr = nweb_.lock();
288 if (!nweb_ptr) {
289 return "";
290 }
291 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
292 if (!setting) {
293 return "";
294 }
295 return setting->UserAgent();
296 }
297
SetCustomUserAgent(const std::string & userAgent)298 ErrCode WebviewController::SetCustomUserAgent(const std::string& userAgent)
299 {
300 auto nweb_ptr = nweb_.lock();
301 if (!nweb_ptr) {
302 return NWebError::INIT_ERROR;
303 }
304 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
305 if (!setting) {
306 return NWebError::INIT_ERROR;
307 }
308 setting->PutUserAgent(userAgent);
309 return NWebError::NO_ERROR;
310 }
311
GetTitle()312 std::string WebviewController::GetTitle()
313 {
314 std::string title = "";
315 auto nweb_ptr = nweb_.lock();
316 if (nweb_ptr) {
317 title = nweb_ptr->Title();
318 }
319 return title;
320 }
321
GetPageHeight()322 int32_t WebviewController::GetPageHeight()
323 {
324 int32_t pageHeight = 0;
325 auto nweb_ptr = nweb_.lock();
326 if (nweb_ptr) {
327 pageHeight = nweb_ptr->ContentHeight();
328 }
329 return pageHeight;
330 }
331
BackOrForward(int32_t step)332 ErrCode WebviewController::BackOrForward(int32_t step)
333 {
334 auto nweb_ptr = nweb_.lock();
335 if (!nweb_ptr) {
336 return INIT_ERROR;
337 }
338
339 nweb_ptr->NavigateBackOrForward(step);
340 return NWebError::NO_ERROR;
341 }
342
StoreWebArchiveCallback(const std::string & baseName,bool autoName,napi_env env,napi_ref jsCallback)343 void WebviewController::StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env,
344 napi_ref jsCallback)
345 {
346 auto nweb_ptr = nweb_.lock();
347 if (!nweb_ptr) {
348 napi_value setResult[RESULT_COUNT] = {0};
349 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
350 napi_get_null(env, &setResult[PARAMONE]);
351
352 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
353 napi_value callback = nullptr;
354 napi_get_reference_value(env, jsCallback, &callback);
355 napi_value callbackResult = nullptr;
356 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
357 napi_delete_reference(env, jsCallback);
358 return;
359 }
360
361 if (jsCallback == nullptr) {
362 return;
363 }
364
365 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
366 callbackImpl->SetCallBack([env, jCallback = std::move(jsCallback)](std::string result) {
367 if (!env) {
368 return;
369 }
370 napi_handle_scope scope = nullptr;
371 napi_open_handle_scope(env, &scope);
372 if (scope == nullptr) {
373 return;
374 }
375
376 napi_value setResult[RESULT_COUNT] = {0};
377 if (result.empty()) {
378 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
379 napi_get_null(env, &setResult[PARAMONE]);
380 } else {
381 napi_get_undefined(env, &setResult[PARAMZERO]);
382 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
383 }
384 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
385 napi_value callback = nullptr;
386 napi_get_reference_value(env, jCallback, &callback);
387 napi_value callbackResult = nullptr;
388 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
389
390 napi_delete_reference(env, jCallback);
391 napi_close_handle_scope(env, scope);
392 });
393 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
394 return;
395 }
396
StoreWebArchivePromise(const std::string & baseName,bool autoName,napi_env env,napi_deferred deferred)397 void WebviewController::StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env,
398 napi_deferred deferred)
399 {
400 auto nweb_ptr = nweb_.lock();
401 if (!nweb_ptr) {
402 napi_value jsResult = nullptr;
403 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
404 napi_reject_deferred(env, deferred, jsResult);
405 return;
406 }
407
408 if (deferred == nullptr) {
409 return;
410 }
411
412 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
413 callbackImpl->SetCallBack([env, deferred](std::string result) {
414 if (!env) {
415 return;
416 }
417 napi_handle_scope scope = nullptr;
418 napi_open_handle_scope(env, &scope);
419 if (scope == nullptr) {
420 return;
421 }
422
423 napi_value setResult[RESULT_COUNT] = {0};
424 setResult[PARAMZERO] = NWebError::BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
425 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
426 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
427 if (!result.empty()) {
428 napi_resolve_deferred(env, deferred, args[PARAMONE]);
429 } else {
430 napi_reject_deferred(env, deferred, args[PARAMZERO]);
431 }
432 napi_close_handle_scope(env, scope);
433 });
434 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
435 return;
436 }
437
CreateWebMessagePorts(std::vector<std::string> & ports)438 ErrCode WebviewController::CreateWebMessagePorts(std::vector<std::string>& ports)
439 {
440 auto nweb_ptr = nweb_.lock();
441 if (!nweb_ptr) {
442 return INIT_ERROR;
443 }
444
445 nweb_ptr->CreateWebMessagePorts(ports);
446 return NWebError::NO_ERROR;
447 }
448
PostWebMessage(std::string & message,std::vector<std::string> & ports,std::string & targetUrl)449 ErrCode WebviewController::PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl)
450 {
451 auto nweb_ptr = nweb_.lock();
452 if (!nweb_ptr) {
453 return INIT_ERROR;
454 }
455
456 nweb_ptr->PostWebMessage(message, ports, targetUrl);
457 return NWebError::NO_ERROR;
458 }
459
WebMessagePort(int32_t nwebId,std::string & port,bool isExtentionType)460 WebMessagePort::WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType)
461 : nweb_(NWebHelper::Instance().GetNWeb(nwebId)), portHandle_(port), isExtentionType_(isExtentionType)
462 {}
463
ClosePort()464 ErrCode WebMessagePort::ClosePort()
465 {
466 auto nweb_ptr = nweb_.lock();
467 if (!nweb_ptr) {
468 return INIT_ERROR;
469 }
470
471 nweb_ptr->ClosePort(portHandle_);
472 portHandle_.clear();
473 return NWebError::NO_ERROR;
474 }
475
PostPortMessage(std::shared_ptr<NWebMessage> data)476 ErrCode WebMessagePort::PostPortMessage(std::shared_ptr<NWebMessage> data)
477 {
478 auto nweb_ptr = nweb_.lock();
479 if (!nweb_ptr) {
480 return INIT_ERROR;
481 }
482
483 if (portHandle_.empty()) {
484 WVLOG_E("can't post message, message port already closed");
485 return CAN_NOT_POST_MESSAGE;
486 }
487 nweb_ptr->PostPortMessage(portHandle_, data);
488 return NWebError::NO_ERROR;
489 }
490
SetPortMessageCallback(std::shared_ptr<NWebValueCallback<std::shared_ptr<NWebMessage>>> callback)491 ErrCode WebMessagePort::SetPortMessageCallback(
492 std::shared_ptr<NWebValueCallback<std::shared_ptr<NWebMessage>>> callback)
493 {
494 auto nweb_ptr = nweb_.lock();
495 if (!nweb_ptr) {
496 return INIT_ERROR;
497 }
498
499 if (portHandle_.empty()) {
500 WVLOG_E("can't register message port callback event, message port already closed");
501 return CAN_NOT_REGISTER_MESSAGE_EVENT;
502 }
503 nweb_ptr->SetPortMessageCallback(portHandle_, callback);
504 return NWebError::NO_ERROR;
505 }
506
GetPortHandle() const507 std::string WebMessagePort::GetPortHandle() const
508 {
509 return portHandle_;
510 }
511
GetHitTestValue()512 HitTestResult WebviewController::GetHitTestValue()
513 {
514 OHOS::NWeb::HitTestResult nwebResult;
515 auto nweb_ptr = nweb_.lock();
516 if (nweb_ptr) {
517 nwebResult = nweb_ptr->GetHitTestResult();
518 nwebResult.SetType(ConverToWebHitTestType(nwebResult.GetType()));
519 }
520 return nwebResult;
521 }
522
RequestFocus()523 void WebviewController::RequestFocus()
524 {
525 auto nweb_ptr = nweb_.lock();
526 if (nweb_ptr) {
527 nweb_ptr->OnFocus();
528 }
529 }
530
GetRawFileUrl(const std::string & fileName,const std::string & bundleName,const std::string & moduleName,std::string & result)531 bool WebviewController::GetRawFileUrl(const std::string &fileName,
532 const std::string& bundleName, const std::string& moduleName, std::string &result)
533 {
534 if (fileName.empty()) {
535 WVLOG_E("File name is empty.");
536 return false;
537 }
538 if (hapPath_.empty()) {
539 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
540 AbilityRuntime::ApplicationContext::GetApplicationContext();
541 std::string packagePath = "file:///" + context->GetBundleCodeDir() + "/";
542 std::string contextBundleName = context->GetBundleName() + "/";
543 std::shared_ptr<AppExecFwk::ApplicationInfo> appInfo = context->GetApplicationInfo();
544 std::string entryDir = appInfo->entryDir;
545 bool isStage = entryDir.find("entry") == std::string::npos ? false : true;
546 result = isStage ? packagePath + "entry/resources/rawfile/" + fileName :
547 packagePath + contextBundleName + "assets/entry/resources/rawfile/" + fileName;
548 } else {
549 std::string appBundleName;
550 std::string appModuleName;
551 result = "resource://RAWFILE/";
552 if (GetAppBundleNameAndModuleName(appBundleName, appModuleName)) {
553 if (appBundleName != bundleName || appModuleName != moduleName) {
554 result += BUNDLE_NAME_PREFIX + bundleName + "/" + MODULE_NAME_PREFIX + moduleName + "/";
555 }
556 }
557 result += fileName;
558 }
559 WVLOG_D("The parsed url is: %{public}s", result.c_str());
560 return true;
561 }
562
ParseUrl(napi_env env,napi_value urlObj,std::string & result)563 bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result)
564 {
565 napi_valuetype valueType = napi_null;
566 napi_typeof(env, urlObj, &valueType);
567 if ((valueType != napi_object) && (valueType != napi_string)) {
568 WVLOG_E("Unable to parse url object.");
569 return false;
570 }
571 if (valueType == napi_string) {
572 NapiParseUtils::ParseString(env, urlObj, result);
573 WVLOG_D("The parsed url is: %{public}s", result.c_str());
574 return true;
575 }
576 napi_value type = nullptr;
577 napi_valuetype typeVlueType = napi_null;
578 napi_get_named_property(env, urlObj, "type", &type);
579 napi_typeof(env, type, &typeVlueType);
580 if (typeVlueType == napi_number) {
581 int32_t typeInteger;
582 NapiParseUtils::ParseInt32(env, type, typeInteger);
583 if (typeInteger == static_cast<int>(ResourceType::RAWFILE)) {
584 napi_value paraArray = nullptr;
585 napi_get_named_property(env, urlObj, "params", ¶Array);
586 bool isArray = false;
587 napi_is_array(env, paraArray, &isArray);
588 if (!isArray) {
589 WVLOG_E("Unable to parse parameter array from url object.");
590 return false;
591 }
592 napi_value fileNameObj;
593 napi_value bundleNameObj;
594 napi_value moduleNameObj;
595 std::string fileName;
596 std::string bundleName;
597 std::string moduleName;
598 napi_get_element(env, paraArray, 0, &fileNameObj);
599 napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj);
600 napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj);
601 NapiParseUtils::ParseString(env, fileNameObj, fileName);
602 NapiParseUtils::ParseString(env, bundleNameObj, bundleName);
603 NapiParseUtils::ParseString(env, moduleNameObj, moduleName);
604 return GetRawFileUrl(fileName, bundleName, moduleName, result);
605 }
606 WVLOG_E("The type parsed from url object is not RAWFILE.");
607 return false;
608 }
609 WVLOG_E("Unable to parse type from url object.");
610 return false;
611 }
612
PostUrl(std::string & url,std::vector<char> & postData)613 ErrCode WebviewController::PostUrl(std::string& url, std::vector<char>& postData)
614 {
615 auto nweb_ptr = nweb_.lock();
616 if (!nweb_ptr) {
617 return INIT_ERROR;
618 }
619 return nweb_ptr->PostUrl(url, postData);
620 }
621
LoadUrl(std::string url)622 ErrCode WebviewController::LoadUrl(std::string url)
623 {
624 auto nweb_ptr = nweb_.lock();
625 if (!nweb_ptr) {
626 return INIT_ERROR;
627 }
628 return nweb_ptr->Load(url);
629 }
630
LoadUrl(std::string url,std::map<std::string,std::string> httpHeaders)631 ErrCode WebviewController::LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders)
632 {
633 auto nweb_ptr = nweb_.lock();
634 if (!nweb_ptr) {
635 return INIT_ERROR;
636 }
637 return nweb_ptr->Load(url, httpHeaders);
638 }
639
LoadData(std::string data,std::string mimeType,std::string encoding,std::string baseUrl,std::string historyUrl)640 ErrCode WebviewController::LoadData(std::string data, std::string mimeType, std::string encoding,
641 std::string baseUrl, std::string historyUrl)
642 {
643 auto nweb_ptr = nweb_.lock();
644 if (!nweb_ptr) {
645 return INIT_ERROR;
646 }
647 if (baseUrl.empty() && historyUrl.empty()) {
648 return nweb_ptr->LoadWithData(data, mimeType, encoding);
649 }
650 return nweb_ptr->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
651 }
652
ConverToWebHitTestType(int hitType)653 int WebviewController::ConverToWebHitTestType(int hitType)
654 {
655 WebHitTestType webHitType;
656 switch (hitType) {
657 case HitTestResult::UNKNOWN_TYPE:
658 webHitType = WebHitTestType::UNKNOWN;
659 break;
660 case HitTestResult::ANCHOR_TYPE:
661 webHitType = WebHitTestType::HTTP;
662 break;
663 case HitTestResult::PHONE_TYPE:
664 webHitType = WebHitTestType::PHONE;
665 break;
666 case HitTestResult::GEO_TYPE:
667 webHitType = WebHitTestType::MAP;
668 break;
669 case HitTestResult::EMAIL_TYPE:
670 webHitType = WebHitTestType::EMAIL;
671 break;
672 case HitTestResult::IMAGE_TYPE:
673 webHitType = WebHitTestType::IMG;
674 break;
675 case HitTestResult::IMAGE_ANCHOR_TYPE:
676 webHitType = WebHitTestType::HTTP_IMG;
677 break;
678 case HitTestResult::SRC_ANCHOR_TYPE:
679 webHitType = WebHitTestType::HTTP;
680 break;
681 case HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
682 webHitType = WebHitTestType::HTTP_IMG;
683 break;
684 case HitTestResult::EDIT_TEXT_TYPE:
685 webHitType = WebHitTestType::EDIT;
686 break;
687 default:
688 webHitType = WebHitTestType::UNKNOWN;
689 break;
690 }
691 return static_cast<int>(webHitType);
692 }
693
GetHitTest()694 int WebviewController::GetHitTest()
695 {
696 auto nweb_ptr = nweb_.lock();
697 if (nweb_ptr) {
698 return ConverToWebHitTestType(nweb_ptr->GetHitTestResult().GetType());
699 }
700 return static_cast<int>(WebHitTestType::UNKNOWN);
701 }
702
703
ClearMatches()704 void WebviewController::ClearMatches()
705 {
706 auto nweb_ptr = nweb_.lock();
707 if (nweb_ptr) {
708 nweb_ptr->ClearMatches();
709 }
710 }
711
SearchNext(bool forward)712 void WebviewController::SearchNext(bool forward)
713 {
714 auto nweb_ptr = nweb_.lock();
715 if (nweb_ptr) {
716 nweb_ptr->FindNext(forward);
717 }
718 }
719
EnableSafeBrowsing(bool enable)720 void WebviewController::EnableSafeBrowsing(bool enable)
721 {
722 auto nweb_ptr = nweb_.lock();
723 if (nweb_ptr) {
724 nweb_ptr->EnableSafeBrowsing(enable);
725 }
726 }
727
IsSafeBrowsingEnabled()728 bool WebviewController::IsSafeBrowsingEnabled()
729 {
730 bool is_safe_browsing_enabled = false;
731 auto nweb_ptr = nweb_.lock();
732 if (nweb_ptr) {
733 is_safe_browsing_enabled = nweb_ptr->IsSafeBrowsingEnabled();
734 }
735 return is_safe_browsing_enabled;
736 }
737
SearchAllAsync(const std::string & searchString)738 void WebviewController::SearchAllAsync(const std::string& searchString)
739 {
740 auto nweb_ptr = nweb_.lock();
741 if (nweb_ptr) {
742 nweb_ptr->FindAllAsync(searchString);
743 }
744 }
745
ClearSslCache()746 void WebviewController::ClearSslCache()
747 {
748 auto nweb_ptr = nweb_.lock();
749 if (nweb_ptr) {
750 nweb_ptr->ClearSslCache();
751 }
752 }
753
ClearClientAuthenticationCache()754 void WebviewController::ClearClientAuthenticationCache()
755 {
756 auto nweb_ptr = nweb_.lock();
757 if (nweb_ptr) {
758 nweb_ptr->ClearClientAuthenticationCache();
759 }
760 }
761
Stop()762 void WebviewController::Stop()
763 {
764 auto nweb_ptr = nweb_.lock();
765 if (nweb_ptr) {
766 nweb_ptr->Stop();
767 }
768 }
769
Zoom(float factor)770 ErrCode WebviewController::Zoom(float factor)
771 {
772 auto nweb_ptr = nweb_.lock();
773 if (!nweb_ptr) {
774 return INIT_ERROR;
775 }
776 ErrCode result = NWebError::NO_ERROR;
777 result = nweb_ptr->Zoom(factor);
778
779 return result;
780 }
781
DeleteJavaScriptRegister(const std::string & objName,const std::vector<std::string> & methodList)782 ErrCode WebviewController::DeleteJavaScriptRegister(const std::string& objName,
783 const std::vector<std::string>& methodList)
784 {
785 auto nweb_ptr = nweb_.lock();
786 if (nweb_ptr) {
787 nweb_ptr->UnregisterArkJSfunction(objName, methodList);
788 }
789
790 if (javaScriptResultCb_) {
791 bool ret = javaScriptResultCb_->DeleteJavaScriptRegister(objName);
792 if (!ret) {
793 return CANNOT_DEL_JAVA_SCRIPT_PROXY;
794 }
795 }
796
797 return NWebError::NO_ERROR;
798 }
799
SetNWebJavaScriptResultCallBack()800 void WebviewController::SetNWebJavaScriptResultCallBack()
801 {
802 auto nweb_ptr = nweb_.lock();
803 if (!nweb_ptr) {
804 return;
805 }
806
807 if (javaScriptResultCb_ && (javaScriptResultCb_->GetNWebId() == id_)) {
808 return;
809 }
810
811 javaScriptResultCb_ = std::make_shared<WebviewJavaScriptResultCallBack>(nweb_, id_);
812 nweb_ptr->SetNWebJavaScriptResultCallBack(javaScriptResultCb_);
813 }
814
RegisterJavaScriptProxy(napi_env env,napi_value obj,const std::string & objName,const std::vector<std::string> & methodList)815 void WebviewController::RegisterJavaScriptProxy(
816 napi_env env, napi_value obj, const std::string& objName, const std::vector<std::string>& methodList)
817 {
818 auto nweb_ptr = nweb_.lock();
819 if (!nweb_ptr) {
820 WVLOG_E("WebviewController::RegisterJavaScriptProxy nweb_ptr is null");
821 return;
822 }
823 JavaScriptOb::ObjectID objId =
824 static_cast<JavaScriptOb::ObjectID>(JavaScriptOb::JavaScriptObjIdErrorCode::WEBCONTROLLERERROR);
825
826 if (!javaScriptResultCb_) {
827 WVLOG_E("WebviewController::RegisterJavaScriptProxy javaScriptResultCb_ is "
828 "null");
829 return;
830 }
831
832 if (methodList.empty()) {
833 WVLOG_E("WebviewController::RegisterJavaScriptProxy methodList is "
834 "empty");
835 return;
836 }
837
838 objId = javaScriptResultCb_->RegisterJavaScriptProxy(env, obj, objName, methodList);
839
840 nweb_ptr->RegisterArkJSfunctionExt(objName, methodList, objId);
841 }
842
RunJavaScriptCallback(const std::string & script,napi_env env,napi_ref jsCallback,bool extention)843 void WebviewController::RunJavaScriptCallback(
844 const std::string& script, napi_env env, napi_ref jsCallback, bool extention)
845 {
846 auto nweb_ptr = nweb_.lock();
847 if (!nweb_ptr) {
848 napi_value setResult[RESULT_COUNT] = {0};
849 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
850 napi_get_null(env, &setResult[PARAMONE]);
851
852 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
853 napi_value callback = nullptr;
854 napi_get_reference_value(env, jsCallback, &callback);
855 napi_value callbackResult = nullptr;
856 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
857 napi_delete_reference(env, jsCallback);
858 return;
859 }
860
861 if (jsCallback == nullptr) {
862 return;
863 }
864
865 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
866 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
867 }
868
RunJavaScriptPromise(const std::string & script,napi_env env,napi_deferred deferred,bool extention)869 void WebviewController::RunJavaScriptPromise(const std::string &script, napi_env env,
870 napi_deferred deferred, bool extention)
871 {
872 auto nweb_ptr = nweb_.lock();
873 if (!nweb_ptr) {
874 napi_value jsResult = nullptr;
875 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
876 napi_reject_deferred(env, deferred, jsResult);
877 return;
878 }
879
880 if (deferred == nullptr) {
881 return;
882 }
883
884 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
885 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
886 }
887
GetUrl()888 std::string WebviewController::GetUrl()
889 {
890 std::string url = "";
891 auto nweb_ptr = nweb_.lock();
892 if (nweb_ptr) {
893 url = nweb_ptr->GetUrl();
894 }
895 return url;
896 }
897
GetOriginalUrl()898 std::string WebviewController::GetOriginalUrl()
899 {
900 std::string url = "";
901 auto nweb_ptr = nweb_.lock();
902 if (nweb_ptr) {
903 url = nweb_ptr->GetOriginalUrl();
904 }
905 return url;
906 }
907
PutNetworkAvailable(bool available)908 void WebviewController::PutNetworkAvailable(bool available)
909 {
910 auto nweb_ptr = nweb_.lock();
911 if (nweb_ptr) {
912 nweb_ptr->PutNetworkAvailable(available);
913 }
914 }
915
HasImagesCallback(napi_env env,napi_ref jsCallback)916 ErrCode WebviewController::HasImagesCallback(napi_env env, napi_ref jsCallback)
917 {
918 auto nweb_ptr = nweb_.lock();
919 if (!nweb_ptr) {
920 napi_value setResult[RESULT_COUNT] = {0};
921 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
922 napi_get_null(env, &setResult[PARAMONE]);
923
924 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
925 napi_value callback = nullptr;
926 napi_get_reference_value(env, jsCallback, &callback);
927 napi_value callbackResult = nullptr;
928 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
929 napi_delete_reference(env, jsCallback);
930 return NWebError::INIT_ERROR;
931 }
932
933 if (jsCallback == nullptr) {
934 return NWebError::PARAM_CHECK_ERROR;
935 }
936
937 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, jsCallback, nullptr);
938 nweb_ptr->HasImages(callbackImpl);
939 return NWebError::NO_ERROR;
940 }
941
HasImagesPromise(napi_env env,napi_deferred deferred)942 ErrCode WebviewController::HasImagesPromise(napi_env env, napi_deferred deferred)
943 {
944 auto nweb_ptr = nweb_.lock();
945 if (!nweb_ptr) {
946 napi_value jsResult = nullptr;
947 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
948 napi_reject_deferred(env, deferred, jsResult);
949 return NWebError::INIT_ERROR;
950 }
951
952 if (deferred == nullptr) {
953 return NWebError::PARAM_CHECK_ERROR;
954 }
955
956 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, nullptr, deferred);
957 nweb_ptr->HasImages(callbackImpl);
958 return NWebError::NO_ERROR;
959 }
960
RemoveCache(bool include_disk_files)961 void WebviewController::RemoveCache(bool include_disk_files)
962 {
963 auto nweb_ptr = nweb_.lock();
964 if (nweb_ptr) {
965 nweb_ptr->RemoveCache(include_disk_files);
966 }
967 }
968
GetHistoryList()969 std::shared_ptr<NWebHistoryList> WebviewController::GetHistoryList()
970 {
971 auto nweb_ptr = nweb_.lock();
972 if (!nweb_ptr) {
973 return nullptr;
974 }
975 return nweb_ptr->GetHistoryList();
976 }
977
GetItem(int32_t index)978 std::shared_ptr<NWebHistoryItem> WebHistoryList::GetItem(int32_t index)
979 {
980 if (!sptrHistoryList_) {
981 return nullptr;
982 }
983 return sptrHistoryList_->GetItem(index);
984 }
985
GetListSize()986 int32_t WebHistoryList::GetListSize()
987 {
988 int32_t listSize = 0;
989
990 if (!sptrHistoryList_) {
991 return listSize;
992 }
993 listSize = sptrHistoryList_->GetListSize();
994 return listSize;
995 }
996
GetFavicon(const void ** data,size_t & width,size_t & height,ImageColorType & colorType,ImageAlphaType & alphaType)997 bool WebviewController::GetFavicon(
998 const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType)
999 {
1000 bool isGetFavicon = false;
1001 auto nweb_ptr = nweb_.lock();
1002 if (nweb_ptr) {
1003 isGetFavicon = nweb_ptr->GetFavicon(data, width, height, colorType, alphaType);
1004 }
1005 return isGetFavicon;
1006 }
1007
SerializeWebState()1008 WebState WebviewController::SerializeWebState()
1009 {
1010 auto nweb_ptr = nweb_.lock();
1011 if (nweb_ptr) {
1012 return nweb_ptr->SerializeWebState();
1013 }
1014 return nullptr;
1015 }
1016
RestoreWebState(WebState state)1017 bool WebviewController::RestoreWebState(WebState state)
1018 {
1019 bool isRestored = false;
1020 auto nweb_ptr = nweb_.lock();
1021 if (nweb_ptr) {
1022 isRestored = nweb_ptr->RestoreWebState(state);
1023 }
1024 return isRestored;
1025 }
1026
ScrollPageDown(bool bottom)1027 void WebviewController::ScrollPageDown(bool bottom)
1028 {
1029 auto nweb_ptr = nweb_.lock();
1030 if (nweb_ptr) {
1031 nweb_ptr->PageDown(bottom);
1032 }
1033 return;
1034 }
1035
ScrollPageUp(bool top)1036 void WebviewController::ScrollPageUp(bool top)
1037 {
1038 auto nweb_ptr = nweb_.lock();
1039 if (nweb_ptr) {
1040 nweb_ptr->PageUp(top);
1041 }
1042 return;
1043 }
1044
ScrollTo(float x,float y)1045 void WebviewController::ScrollTo(float x, float y)
1046 {
1047 auto nweb_ptr = nweb_.lock();
1048 if (nweb_ptr) {
1049 nweb_ptr->ScrollTo(x, y);
1050 }
1051 return;
1052 }
1053
ScrollBy(float deltaX,float deltaY)1054 void WebviewController::ScrollBy(float deltaX, float deltaY)
1055 {
1056 auto nweb_ptr = nweb_.lock();
1057 if (nweb_ptr) {
1058 nweb_ptr->ScrollBy(deltaX, deltaY);
1059 }
1060 return;
1061 }
1062
SlideScroll(float vx,float vy)1063 void WebviewController::SlideScroll(float vx, float vy)
1064 {
1065 auto nweb_ptr = nweb_.lock();
1066 if (nweb_ptr) {
1067 nweb_ptr->SlideScroll(vx, vy);
1068 }
1069 return;
1070 }
1071
InnerSetHapPath(const std::string & hapPath)1072 void WebviewController::InnerSetHapPath(const std::string &hapPath)
1073 {
1074 hapPath_ = hapPath;
1075 }
1076
GetCertChainDerData(std::vector<std::string> & certChainDerData)1077 bool WebviewController::GetCertChainDerData(std::vector<std::string> &certChainDerData)
1078 {
1079 auto nweb_ptr = nweb_.lock();
1080 if (!nweb_ptr) {
1081 WVLOG_E("GetCertChainDerData failed, nweb ptr is null");
1082 return false;
1083 }
1084
1085 return nweb_ptr->GetCertChainDerData(certChainDerData, true);
1086 }
1087
SetAudioMuted(bool muted)1088 ErrCode WebviewController::SetAudioMuted(bool muted)
1089 {
1090 auto nweb_ptr = nweb_.lock();
1091 if (!nweb_ptr) {
1092 return NWebError::INIT_ERROR;
1093 }
1094
1095 nweb_ptr->SetAudioMuted(muted);
1096 return NWebError::NO_ERROR;
1097 }
1098
PrefetchPage(std::string & url,std::map<std::string,std::string> additionalHttpHeaders)1099 ErrCode WebviewController::PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders)
1100 {
1101 auto nweb_ptr = nweb_.lock();
1102 if (!nweb_ptr) {
1103 return NWebError::INIT_ERROR;
1104 }
1105
1106 nweb_ptr->PrefetchPage(url, additionalHttpHeaders);
1107 return NWebError::NO_ERROR;
1108 }
1109
OnStartLayoutWrite(const std::string & jobId,const PrintAttributesAdapter & oldAttrs,const PrintAttributesAdapter & newAttrs,uint32_t fd,std::function<void (std::string,uint32_t)> writeResultCallback)1110 void WebPrintDocument::OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs,
1111 const PrintAttributesAdapter& newAttrs, uint32_t fd, std::function<void(std::string, uint32_t)> writeResultCallback)
1112 {
1113 if (printDocAdapter_) {
1114 printDocAdapter_->OnStartLayoutWrite(jobId, oldAttrs, newAttrs, fd, writeResultCallback);
1115 }
1116 }
1117
OnJobStateChanged(const std::string & jobId,uint32_t state)1118 void WebPrintDocument::OnJobStateChanged(const std::string& jobId, uint32_t state)
1119 {
1120 if (printDocAdapter_) {
1121 printDocAdapter_->OnJobStateChanged(jobId, state);
1122 }
1123 }
1124
CreateWebPrintDocumentAdapter(const std::string & jobName)1125 void* WebviewController::CreateWebPrintDocumentAdapter(const std::string& jobName)
1126 {
1127 auto nweb_ptr = nweb_.lock();
1128 if (!nweb_ptr) {
1129 return nullptr;
1130 }
1131 return nweb_ptr->CreateWebPrintDocumentAdapter(jobName);
1132 }
1133
GetSecurityLevel()1134 int WebviewController::GetSecurityLevel()
1135 {
1136 auto nweb_ptr = nweb_.lock();
1137 if (!nweb_ptr) {
1138 return static_cast<int>(SecurityLevel::NONE);
1139 }
1140
1141 int nwebSecurityLevel = nweb_ptr->GetSecurityLevel();
1142 SecurityLevel securityLevel;
1143 switch (nwebSecurityLevel) {
1144 case static_cast<int>(CoreSecurityLevel::NONE):
1145 securityLevel = SecurityLevel::NONE;
1146 break;
1147 case static_cast<int>(CoreSecurityLevel::SECURE):
1148 securityLevel = SecurityLevel::SECURE;
1149 break;
1150 case static_cast<int>(CoreSecurityLevel::WARNING):
1151 securityLevel = SecurityLevel::WARNING;
1152 break;
1153 case static_cast<int>(CoreSecurityLevel::DANGEROUS):
1154 securityLevel = SecurityLevel::DANGEROUS;
1155 break;
1156 default:
1157 securityLevel = SecurityLevel::NONE;
1158 break;
1159 }
1160
1161 return static_cast<int>(securityLevel);
1162 }
1163
IsIncognitoMode()1164 bool WebviewController::IsIncognitoMode()
1165 {
1166 bool incognitoMode = false;
1167 auto nweb_ptr = nweb_.lock();
1168 if (nweb_ptr) {
1169 incognitoMode = nweb_ptr->IsIncognitoMode();
1170 }
1171 return incognitoMode;
1172 }
1173 } // namespace NWeb
1174 } // namespace OHOS
1175