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 #include <securec.h>
20 #include <regex>
21
22 #include "application_context.h"
23 #include "business_error.h"
24 #include "napi_parse_utils.h"
25 #include "ohos_resource_adapter_impl.h"
26
27 #include "native_arkweb_utils.h"
28 #include "native_interface_arkweb.h"
29 #include "native_media_player_impl.h"
30
31 #include "nweb_log.h"
32 #include "nweb_store_web_archive_callback.h"
33 #include "web_errors.h"
34 #include "webview_hasimage_callback.h"
35 #include "webview_javascript_execute_callback.h"
36 #include "webview_javascript_result_callback.h"
37
38 #include "nweb_precompile_callback.h"
39 #include "nweb_cache_options_impl.h"
40
41 namespace {
42 constexpr int32_t PARAMZERO = 0;
43 constexpr int32_t PARAMONE = 1;
44 constexpr int32_t RESULT_COUNT = 2;
45 const std::string BUNDLE_NAME_PREFIX = "bundleName:";
46 const std::string MODULE_NAME_PREFIX = "moduleName:";
47 } // namespace
48
49 namespace OHOS {
50 namespace NWeb {
51 namespace {
52 constexpr uint32_t URL_MAXIMUM = 2048;
GetAppBundleNameAndModuleName(std::string & bundleName,std::string & moduleName)53 bool GetAppBundleNameAndModuleName(std::string& bundleName, std::string& moduleName)
54 {
55 static std::string applicationBundleName;
56 static std::string applicationModuleName;
57 if (!applicationBundleName.empty() && !applicationModuleName.empty()) {
58 bundleName = applicationBundleName;
59 moduleName = applicationModuleName;
60 return true;
61 }
62 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
63 AbilityRuntime::ApplicationContext::GetApplicationContext();
64 if (!context) {
65 WVLOG_E("Failed to get application context.");
66 return false;
67 }
68 auto resourceManager = context->GetResourceManager();
69 if (!resourceManager) {
70 WVLOG_E("Failed to get resource manager.");
71 return false;
72 }
73 applicationBundleName = resourceManager->bundleInfo.first;
74 applicationModuleName = resourceManager->bundleInfo.second;
75 bundleName = applicationBundleName;
76 moduleName = applicationModuleName;
77 WVLOG_D("application bundleName: %{public}s, moduleName: %{public}s", bundleName.c_str(), moduleName.c_str());
78 return true;
79 }
80 }
81 using namespace NWebError;
82 std::unordered_map<int32_t, WebviewController*> g_webview_controller_map;
83 std::string WebviewController::customeSchemeCmdLine_ = "";
84 bool WebviewController::existNweb_ = false;
85 bool WebviewController::webDebuggingAccess_ = false;
86 std::set<std::string> WebviewController::webTagSet_;
87 int32_t WebviewController::webTagStrId_ = 0;
88
WebviewController(int32_t nwebId)89 WebviewController::WebviewController(int32_t nwebId) : nwebId_(nwebId)
90 {
91 if (IsInit()) {
92 std::unique_lock<std::mutex> lk(webMtx_);
93 g_webview_controller_map.emplace(nwebId, this);
94 }
95 }
96
WebviewController(const std::string & webTag)97 WebviewController::WebviewController(const std::string& webTag) : webTag_(webTag)
98 {
99 NWebHelper::Instance().SetWebTag(-1, webTag_.c_str());
100 }
101
~WebviewController()102 WebviewController::~WebviewController()
103 {
104 std::unique_lock<std::mutex> lk(webMtx_);
105 g_webview_controller_map.erase(nwebId_);
106 }
107
SetWebId(int32_t nwebId)108 void WebviewController::SetWebId(int32_t nwebId)
109 {
110 nwebId_ = nwebId;
111 std::unique_lock<std::mutex> lk(webMtx_);
112 g_webview_controller_map.emplace(nwebId, this);
113
114 if (webTag_.empty()) {
115 WVLOG_I("native webtag is empty, don't care because it's not a native instance");
116 return;
117 }
118
119 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
120 if (nweb_ptr) {
121 OH_NativeArkWeb_BindWebTagToWebInstance(webTag_.c_str(), nweb_ptr);
122 NWebHelper::Instance().SetWebTag(nwebId_, webTag_.c_str());
123 }
124 SetNWebJavaScriptResultCallBack();
125 NativeArkWeb_OnValidCallback validCallback = OH_NativeArkWeb_GetJavaScriptProxyValidCallback(webTag_.c_str());
126 if (validCallback) {
127 WVLOG_I("native validCallback start to call");
128 (*validCallback)(webTag_.c_str());
129 } else {
130 WVLOG_W("native validCallback is null, callback nothing");
131 }
132 }
133
FromID(int32_t nwebId)134 WebviewController* WebviewController::FromID(int32_t nwebId)
135 {
136 std::unique_lock<std::mutex> lk(webMtx_);
137 if (auto it = g_webview_controller_map.find(nwebId); it != g_webview_controller_map.end()) {
138 auto control = it->second;
139 return control;
140 }
141 return nullptr;
142 }
143
InnerCompleteWindowNew(int32_t parentNwebId)144 void WebviewController::InnerCompleteWindowNew(int32_t parentNwebId)
145 {
146 WVLOG_D("WebviewController::InnerCompleteWindowNew parentNwebId == "
147 "%{public}d ",
148 parentNwebId);
149 if (parentNwebId < 0) {
150 WVLOG_E("WebviewController::InnerCompleteWindowNew parentNwebId == %{public}d "
151 "error",
152 parentNwebId);
153 return;
154 }
155 auto parentControl = FromID(parentNwebId);
156 if (!parentControl || !(parentControl->javaScriptResultCb_)) {
157 WVLOG_E("WebviewController::InnerCompleteWindowNew parentControl or "
158 "javaScriptResultCb_ is null");
159 return;
160 }
161 auto objs = parentControl->javaScriptResultCb_->GetNamedObjects();
162 SetNWebJavaScriptResultCallBack();
163 for (auto it = objs.begin(); it != objs.end(); it++) {
164 if (it->second && IsInit()) {
165 RegisterJavaScriptProxy(
166 it->second->GetEnv(), it->second->GetValue(), it->first,
167 it->second->GetSyncMethodNames(), it->second->GetAsyncMethodNames());
168 }
169 }
170 }
171
IsInit()172 bool WebviewController::IsInit()
173 {
174 return NWebHelper::Instance().GetNWeb(nwebId_) ? true : false;
175 }
176
AccessForward()177 bool WebviewController::AccessForward()
178 {
179 bool access = false;
180 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
181 if (nweb_ptr) {
182 access = nweb_ptr->IsNavigateForwardAllowed();
183 }
184 return access;
185 }
186
AccessBackward()187 bool WebviewController::AccessBackward()
188 {
189 bool access = false;
190 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
191 if (nweb_ptr) {
192 access = nweb_ptr->IsNavigatebackwardAllowed();
193 }
194 return access;
195 }
196
AccessStep(int32_t step)197 bool WebviewController::AccessStep(int32_t step)
198 {
199 bool access = false;
200 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
201 if (nweb_ptr) {
202 access = nweb_ptr->CanNavigateBackOrForward(step);
203 }
204 return access;
205 }
206
ClearHistory()207 void WebviewController::ClearHistory()
208 {
209 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
210 if (nweb_ptr) {
211 nweb_ptr->DeleteNavigateHistory();
212 }
213 }
214
Forward()215 void WebviewController::Forward()
216 {
217 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
218 if (nweb_ptr) {
219 nweb_ptr->NavigateForward();
220 }
221 }
222
Backward()223 void WebviewController::Backward()
224 {
225 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
226 if (nweb_ptr) {
227 nweb_ptr->NavigateBack();
228 }
229 }
230
OnActive()231 void WebviewController::OnActive()
232 {
233 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
234 if (nweb_ptr) {
235 nweb_ptr->OnContinue();
236 }
237 }
238
OnInactive()239 void WebviewController::OnInactive()
240 {
241 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
242 if (nweb_ptr) {
243 nweb_ptr->OnPause();
244 }
245 }
246
Refresh()247 void WebviewController::Refresh()
248 {
249 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
250 if (nweb_ptr) {
251 nweb_ptr->Reload();
252 }
253 }
254
ZoomIn()255 ErrCode WebviewController::ZoomIn()
256 {
257 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
258 if (!nweb_ptr) {
259 return INIT_ERROR;
260 }
261 ErrCode result = NWebError::NO_ERROR;
262 result = nweb_ptr->ZoomIn();
263
264 return result;
265 }
266
ZoomOut()267 ErrCode WebviewController::ZoomOut()
268 {
269 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
270 if (!nweb_ptr) {
271 return INIT_ERROR;
272 }
273 ErrCode result = NWebError::NO_ERROR;
274 result = nweb_ptr->ZoomOut();
275
276 return result;
277 }
278
GetWebId() const279 int32_t WebviewController::GetWebId() const
280 {
281 int32_t webId = -1;
282 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
283 if (nweb_ptr) {
284 webId = static_cast<int32_t>(nweb_ptr->GetWebId());
285 }
286 return webId;
287 }
288
GetUserAgent()289 std::string WebviewController::GetUserAgent()
290 {
291 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
292 if (!nweb_ptr) {
293 return "";
294 }
295 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
296 if (!setting) {
297 return "";
298 }
299 return setting->DefaultUserAgent();
300 }
301
GetCustomUserAgent() const302 std::string WebviewController::GetCustomUserAgent() const
303 {
304 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
305 if (!nweb_ptr) {
306 return "";
307 }
308 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
309 if (!setting) {
310 return "";
311 }
312 return setting->UserAgent();
313 }
314
SetCustomUserAgent(const std::string & userAgent)315 ErrCode WebviewController::SetCustomUserAgent(const std::string& userAgent)
316 {
317 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
318 if (!nweb_ptr) {
319 return NWebError::INIT_ERROR;
320 }
321 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
322 if (!setting) {
323 return NWebError::INIT_ERROR;
324 }
325 setting->PutUserAgent(userAgent);
326 return NWebError::NO_ERROR;
327 }
328
GetTitle()329 std::string WebviewController::GetTitle()
330 {
331 std::string title = "";
332 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
333 if (nweb_ptr) {
334 title = nweb_ptr->Title();
335 }
336 return title;
337 }
338
GetPageHeight()339 int32_t WebviewController::GetPageHeight()
340 {
341 int32_t pageHeight = 0;
342 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
343 if (nweb_ptr) {
344 pageHeight = nweb_ptr->ContentHeight();
345 }
346 return pageHeight;
347 }
348
BackOrForward(int32_t step)349 ErrCode WebviewController::BackOrForward(int32_t step)
350 {
351 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
352 if (!nweb_ptr) {
353 return INIT_ERROR;
354 }
355
356 nweb_ptr->NavigateBackOrForward(step);
357 return NWebError::NO_ERROR;
358 }
359
StoreWebArchiveCallback(const std::string & baseName,bool autoName,napi_env env,napi_ref jsCallback)360 void WebviewController::StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env,
361 napi_ref jsCallback)
362 {
363 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
364 if (!nweb_ptr) {
365 napi_value setResult[RESULT_COUNT] = {0};
366 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
367 napi_get_null(env, &setResult[PARAMONE]);
368
369 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
370 napi_value callback = nullptr;
371 napi_get_reference_value(env, jsCallback, &callback);
372 napi_value callbackResult = nullptr;
373 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
374 napi_delete_reference(env, jsCallback);
375 return;
376 }
377
378 if (jsCallback == nullptr) {
379 return;
380 }
381
382 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
383 callbackImpl->SetCallBack([env, jCallback = std::move(jsCallback)](std::string result) {
384 if (!env) {
385 return;
386 }
387 napi_handle_scope scope = nullptr;
388 napi_open_handle_scope(env, &scope);
389 if (scope == nullptr) {
390 return;
391 }
392
393 napi_value setResult[RESULT_COUNT] = {0};
394 if (result.empty()) {
395 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
396 napi_get_null(env, &setResult[PARAMONE]);
397 } else {
398 napi_get_undefined(env, &setResult[PARAMZERO]);
399 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
400 }
401 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
402 napi_value callback = nullptr;
403 napi_get_reference_value(env, jCallback, &callback);
404 napi_value callbackResult = nullptr;
405 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
406
407 napi_delete_reference(env, jCallback);
408 napi_close_handle_scope(env, scope);
409 });
410 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
411 return;
412 }
413
StoreWebArchivePromise(const std::string & baseName,bool autoName,napi_env env,napi_deferred deferred)414 void WebviewController::StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env,
415 napi_deferred deferred)
416 {
417 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
418 if (!nweb_ptr) {
419 napi_value jsResult = nullptr;
420 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
421 napi_reject_deferred(env, deferred, jsResult);
422 return;
423 }
424
425 if (deferred == nullptr) {
426 return;
427 }
428
429 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebStoreWebArchiveCallback>();
430 callbackImpl->SetCallBack([env, deferred](std::string result) {
431 if (!env) {
432 return;
433 }
434 napi_handle_scope scope = nullptr;
435 napi_open_handle_scope(env, &scope);
436 if (scope == nullptr) {
437 return;
438 }
439
440 napi_value setResult[RESULT_COUNT] = {0};
441 setResult[PARAMZERO] = NWebError::BusinessError::CreateError(env, NWebError::INVALID_RESOURCE);
442 napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &setResult[PARAMONE]);
443 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
444 if (!result.empty()) {
445 napi_resolve_deferred(env, deferred, args[PARAMONE]);
446 } else {
447 napi_reject_deferred(env, deferred, args[PARAMZERO]);
448 }
449 napi_close_handle_scope(env, scope);
450 });
451 nweb_ptr->StoreWebArchive(baseName, autoName, callbackImpl);
452 return;
453 }
454
CreateWebMessagePorts()455 std::vector<std::string> WebviewController::CreateWebMessagePorts()
456 {
457 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
458 if (!nweb_ptr) {
459 std::vector<std::string> empty;
460 return empty;
461 }
462
463 return nweb_ptr->CreateWebMessagePorts();
464 }
465
PostWebMessage(std::string & message,std::vector<std::string> & ports,std::string & targetUrl)466 ErrCode WebviewController::PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl)
467 {
468 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
469 if (!nweb_ptr) {
470 return INIT_ERROR;
471 }
472
473 nweb_ptr->PostWebMessage(message, ports, targetUrl);
474 return NWebError::NO_ERROR;
475 }
476
WebMessagePort(int32_t nwebId,std::string & port,bool isExtentionType)477 WebMessagePort::WebMessagePort(int32_t nwebId, std::string& port, bool isExtentionType)
478 : nwebId_(nwebId), portHandle_(port), isExtentionType_(isExtentionType)
479 {}
480
ClosePort()481 ErrCode WebMessagePort::ClosePort()
482 {
483 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
484 if (!nweb_ptr) {
485 return INIT_ERROR;
486 }
487
488 nweb_ptr->ClosePort(portHandle_);
489 portHandle_.clear();
490 return NWebError::NO_ERROR;
491 }
492
PostPortMessage(std::shared_ptr<NWebMessage> data)493 ErrCode WebMessagePort::PostPortMessage(std::shared_ptr<NWebMessage> data)
494 {
495 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
496 if (!nweb_ptr) {
497 return INIT_ERROR;
498 }
499
500 if (portHandle_.empty()) {
501 WVLOG_E("can't post message, message port already closed");
502 return CAN_NOT_POST_MESSAGE;
503 }
504 nweb_ptr->PostPortMessage(portHandle_, data);
505 return NWebError::NO_ERROR;
506 }
507
SetPortMessageCallback(std::shared_ptr<NWebMessageValueCallback> callback)508 ErrCode WebMessagePort::SetPortMessageCallback(
509 std::shared_ptr<NWebMessageValueCallback> callback)
510 {
511 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
512 if (!nweb_ptr) {
513 return INIT_ERROR;
514 }
515
516 if (portHandle_.empty()) {
517 WVLOG_E("can't register message port callback event, message port already closed");
518 return CAN_NOT_REGISTER_MESSAGE_EVENT;
519 }
520 nweb_ptr->SetPortMessageCallback(portHandle_, callback);
521 return NWebError::NO_ERROR;
522 }
523
GetPortHandle() const524 std::string WebMessagePort::GetPortHandle() const
525 {
526 return portHandle_;
527 }
528
GetHitTestValue()529 std::shared_ptr<HitTestResult> WebviewController::GetHitTestValue()
530 {
531 std::shared_ptr<HitTestResult> nwebResult;
532 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
533 if (nweb_ptr) {
534 nwebResult = nweb_ptr->GetHitTestResult();
535 if (nwebResult) {
536 nwebResult->SetType(ConverToWebHitTestType(nwebResult->GetType()));
537 } else {
538 nwebResult->SetType(ConverToWebHitTestType(HitTestResult::UNKNOWN_TYPE));
539 }
540 }
541 return nwebResult;
542 }
543
RequestFocus()544 void WebviewController::RequestFocus()
545 {
546 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
547 if (nweb_ptr) {
548 nweb_ptr->OnFocus();
549 }
550 }
551
GenerateWebTag()552 std::string WebviewController::GenerateWebTag()
553 {
554 std::string webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
555 while (WebviewController::webTagSet_.find(webTag) != WebviewController::webTagSet_.end()) {
556 WebviewController::webTagStrId_++;
557 webTag = "arkweb:" + std::to_string(WebviewController::webTagStrId_);
558 }
559 return webTag;
560 }
561
GetRawFileUrl(const std::string & fileName,const std::string & bundleName,const std::string & moduleName,std::string & result)562 bool WebviewController::GetRawFileUrl(const std::string &fileName,
563 const std::string& bundleName, const std::string& moduleName, std::string &result)
564 {
565 if (fileName.empty()) {
566 WVLOG_E("File name is empty.");
567 return false;
568 }
569 if (hapPath_.empty()) {
570 std::shared_ptr<AbilityRuntime::ApplicationContext> context =
571 AbilityRuntime::ApplicationContext::GetApplicationContext();
572 std::string packagePath = "file:///" + context->GetBundleCodeDir() + "/";
573 std::string contextBundleName = context->GetBundleName() + "/";
574 std::shared_ptr<AppExecFwk::ApplicationInfo> appInfo = context->GetApplicationInfo();
575 std::string entryDir = appInfo->entryDir;
576 bool isStage = entryDir.find("entry") == std::string::npos ? false : true;
577 result = isStage ? packagePath + "entry/resources/rawfile/" + fileName :
578 packagePath + contextBundleName + "assets/entry/resources/rawfile/" + fileName;
579 } else {
580 std::string appBundleName;
581 std::string appModuleName;
582 result = "resource://RAWFILE/";
583 if (!bundleName.empty() && !moduleName.empty() &&
584 GetAppBundleNameAndModuleName(appBundleName, appModuleName)) {
585 if (appBundleName != bundleName || appModuleName != moduleName) {
586 result += BUNDLE_NAME_PREFIX + bundleName + "/" + MODULE_NAME_PREFIX + moduleName + "/";
587 }
588 }
589 result += fileName;
590 }
591 WVLOG_D("The parsed url is: %{public}s", result.c_str());
592 return true;
593 }
594
ParseUrl(napi_env env,napi_value urlObj,std::string & result)595 bool WebviewController::ParseUrl(napi_env env, napi_value urlObj, std::string& result)
596 {
597 napi_valuetype valueType = napi_null;
598 napi_typeof(env, urlObj, &valueType);
599 if ((valueType != napi_object) && (valueType != napi_string)) {
600 WVLOG_E("Unable to parse url object.");
601 return false;
602 }
603 if (valueType == napi_string) {
604 NapiParseUtils::ParseString(env, urlObj, result);
605 WVLOG_D("The parsed url is: %{public}s", result.c_str());
606 return true;
607 }
608 napi_value type = nullptr;
609 napi_valuetype typeVlueType = napi_null;
610 napi_get_named_property(env, urlObj, "type", &type);
611 napi_typeof(env, type, &typeVlueType);
612 if (typeVlueType == napi_number) {
613 int32_t typeInteger;
614 NapiParseUtils::ParseInt32(env, type, typeInteger);
615 if (typeInteger == static_cast<int>(ResourceType::RAWFILE)) {
616 return ParseRawFileUrl(env, urlObj, result);
617 } else if (typeInteger == static_cast<int>(ResourceType::STRING)) {
618 if (!GetResourceUrl(env, urlObj, result)) {
619 WVLOG_E("Unable to parse string from url object.");
620 return false;
621 }
622 return true;
623 }
624 WVLOG_E("The type parsed from url object is not RAWFILE.");
625 return false;
626 }
627 WVLOG_E("Unable to parse type from url object.");
628 return false;
629 }
630
ParseRawFileUrl(napi_env env,napi_value urlObj,std::string & result)631 bool WebviewController::ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result)
632 {
633 napi_value paraArray = nullptr;
634 napi_get_named_property(env, urlObj, "params", ¶Array);
635 bool isArray = false;
636 napi_is_array(env, paraArray, &isArray);
637 if (!isArray) {
638 WVLOG_E("Unable to parse parameter array from url object.");
639 return false;
640 }
641 napi_value fileNameObj;
642 napi_value bundleNameObj;
643 napi_value moduleNameObj;
644 std::string fileName;
645 std::string bundleName;
646 std::string moduleName;
647 napi_get_element(env, paraArray, 0, &fileNameObj);
648 napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj);
649 napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj);
650 NapiParseUtils::ParseString(env, fileNameObj, fileName);
651 NapiParseUtils::ParseString(env, bundleNameObj, bundleName);
652 NapiParseUtils::ParseString(env, moduleNameObj, moduleName);
653 return GetRawFileUrl(fileName, bundleName, moduleName, result);
654 }
655
GetResourceUrl(napi_env env,napi_value urlObj,std::string & result)656 bool WebviewController::GetResourceUrl(napi_env env, napi_value urlObj, std::string& result)
657 {
658 napi_value resIdObj = nullptr;
659 napi_value bundleNameObj = nullptr;
660 napi_value moduleNameObj = nullptr;
661
662 int32_t resId;
663 std::string bundleName;
664 std::string moduleName;
665
666 if ((napi_get_named_property(env, urlObj, "id", &resIdObj) != napi_ok) ||
667 (napi_get_named_property(env, urlObj, "bundleName", &bundleNameObj) != napi_ok) ||
668 (napi_get_named_property(env, urlObj, "moduleName", &moduleNameObj) != napi_ok)) {
669 return false;
670 }
671
672 if (!NapiParseUtils::ParseInt32(env, resIdObj, resId) ||
673 !NapiParseUtils::ParseString(env, bundleNameObj, bundleName) ||
674 !NapiParseUtils::ParseString(env, moduleNameObj, moduleName)) {
675 return false;
676 }
677
678 if (OhosResourceAdapterImpl::GetResourceString(bundleName, moduleName, resId, result)) {
679 return true;
680 }
681 return false;
682 }
683
PostUrl(std::string & url,std::vector<char> & postData)684 ErrCode WebviewController::PostUrl(std::string& url, std::vector<char>& postData)
685 {
686 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
687 if (!nweb_ptr) {
688 return INIT_ERROR;
689 }
690 return nweb_ptr->PostUrl(url, postData);
691 }
692
LoadUrl(std::string url)693 ErrCode WebviewController::LoadUrl(std::string url)
694 {
695 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
696 if (!nweb_ptr) {
697 return INIT_ERROR;
698 }
699 return nweb_ptr->Load(url);
700 }
701
LoadUrl(std::string url,std::map<std::string,std::string> httpHeaders)702 ErrCode WebviewController::LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders)
703 {
704 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
705 if (!nweb_ptr) {
706 return INIT_ERROR;
707 }
708 return nweb_ptr->Load(url, httpHeaders);
709 }
710
LoadData(std::string data,std::string mimeType,std::string encoding,std::string baseUrl,std::string historyUrl)711 ErrCode WebviewController::LoadData(std::string data, std::string mimeType, std::string encoding,
712 std::string baseUrl, std::string historyUrl)
713 {
714 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
715 if (!nweb_ptr) {
716 return INIT_ERROR;
717 }
718 if (baseUrl.empty() && historyUrl.empty()) {
719 return nweb_ptr->LoadWithData(data, mimeType, encoding);
720 }
721 return nweb_ptr->LoadWithDataAndBaseUrl(baseUrl, data, mimeType, encoding, historyUrl);
722 }
723
ConverToWebHitTestType(int hitType)724 int WebviewController::ConverToWebHitTestType(int hitType)
725 {
726 WebHitTestType webHitType;
727 switch (hitType) {
728 case HitTestResult::UNKNOWN_TYPE:
729 webHitType = WebHitTestType::UNKNOWN;
730 break;
731 case HitTestResult::ANCHOR_TYPE:
732 webHitType = WebHitTestType::HTTP;
733 break;
734 case HitTestResult::PHONE_TYPE:
735 webHitType = WebHitTestType::PHONE;
736 break;
737 case HitTestResult::GEO_TYPE:
738 webHitType = WebHitTestType::MAP;
739 break;
740 case HitTestResult::EMAIL_TYPE:
741 webHitType = WebHitTestType::EMAIL;
742 break;
743 case HitTestResult::IMAGE_TYPE:
744 webHitType = WebHitTestType::IMG;
745 break;
746 case HitTestResult::IMAGE_ANCHOR_TYPE:
747 webHitType = WebHitTestType::HTTP_IMG;
748 break;
749 case HitTestResult::SRC_ANCHOR_TYPE:
750 webHitType = WebHitTestType::HTTP;
751 break;
752 case HitTestResult::SRC_IMAGE_ANCHOR_TYPE:
753 webHitType = WebHitTestType::HTTP_IMG;
754 break;
755 case HitTestResult::EDIT_TEXT_TYPE:
756 webHitType = WebHitTestType::EDIT;
757 break;
758 default:
759 webHitType = WebHitTestType::UNKNOWN;
760 break;
761 }
762 return static_cast<int>(webHitType);
763 }
764
GetHitTest()765 int WebviewController::GetHitTest()
766 {
767 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
768 if (nweb_ptr) {
769 std::shared_ptr<HitTestResult> nwebResult = nweb_ptr->GetHitTestResult();
770 if (nwebResult) {
771 return ConverToWebHitTestType(nwebResult->GetType());
772 } else {
773 return ConverToWebHitTestType(HitTestResult::UNKNOWN_TYPE);
774 }
775 }
776 return static_cast<int>(WebHitTestType::UNKNOWN);
777 }
778
779
ClearMatches()780 void WebviewController::ClearMatches()
781 {
782 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
783 if (nweb_ptr) {
784 nweb_ptr->ClearMatches();
785 }
786 }
787
SearchNext(bool forward)788 void WebviewController::SearchNext(bool forward)
789 {
790 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
791 if (nweb_ptr) {
792 nweb_ptr->FindNext(forward);
793 }
794 }
795
EnableSafeBrowsing(bool enable)796 void WebviewController::EnableSafeBrowsing(bool enable)
797 {
798 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
799 if (nweb_ptr) {
800 nweb_ptr->EnableSafeBrowsing(enable);
801 }
802 }
803
IsSafeBrowsingEnabled()804 bool WebviewController::IsSafeBrowsingEnabled()
805 {
806 bool isSafeBrowsingEnabled = false;
807 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
808 if (nweb_ptr) {
809 isSafeBrowsingEnabled = nweb_ptr->IsSafeBrowsingEnabled();
810 }
811 return isSafeBrowsingEnabled;
812 }
813
SearchAllAsync(const std::string & searchString)814 void WebviewController::SearchAllAsync(const std::string& searchString)
815 {
816 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
817 if (nweb_ptr) {
818 nweb_ptr->FindAllAsync(searchString);
819 }
820 }
821
ClearSslCache()822 void WebviewController::ClearSslCache()
823 {
824 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
825 if (nweb_ptr) {
826 nweb_ptr->ClearSslCache();
827 }
828 }
829
ClearClientAuthenticationCache()830 void WebviewController::ClearClientAuthenticationCache()
831 {
832 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
833 if (nweb_ptr) {
834 nweb_ptr->ClearClientAuthenticationCache();
835 }
836 }
837
Stop()838 void WebviewController::Stop()
839 {
840 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
841 if (nweb_ptr) {
842 nweb_ptr->Stop();
843 }
844 }
845
Zoom(float factor)846 ErrCode WebviewController::Zoom(float factor)
847 {
848 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
849 if (!nweb_ptr) {
850 return INIT_ERROR;
851 }
852 ErrCode result = NWebError::NO_ERROR;
853 result = nweb_ptr->Zoom(factor);
854
855 return result;
856 }
857
DeleteJavaScriptRegister(const std::string & objName,const std::vector<std::string> & methodList)858 ErrCode WebviewController::DeleteJavaScriptRegister(const std::string& objName,
859 const std::vector<std::string>& methodList)
860 {
861 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
862 if (nweb_ptr) {
863 nweb_ptr->UnregisterArkJSfunction(objName, methodList);
864 }
865
866 if (javaScriptResultCb_) {
867 bool ret = javaScriptResultCb_->DeleteJavaScriptRegister(objName);
868 if (!ret) {
869 return CANNOT_DEL_JAVA_SCRIPT_PROXY;
870 }
871 }
872
873 return NWebError::NO_ERROR;
874 }
875
SetNWebJavaScriptResultCallBack()876 void WebviewController::SetNWebJavaScriptResultCallBack()
877 {
878 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
879 if (!nweb_ptr) {
880 return;
881 }
882
883 if (javaScriptResultCb_ && (javaScriptResultCb_->GetNWebId() == nwebId_)) {
884 return;
885 }
886
887 javaScriptResultCb_ = std::make_shared<WebviewJavaScriptResultCallBack>(nwebId_);
888 nweb_ptr->SetNWebJavaScriptResultCallBack(javaScriptResultCb_);
889 }
890
RegisterJavaScriptProxy(napi_env env,napi_value obj,const std::string & objName,const std::vector<std::string> & syncMethodList,const std::vector<std::string> & asyncMethodList)891 void WebviewController::RegisterJavaScriptProxy(
892 napi_env env, napi_value obj, const std::string& objName,
893 const std::vector<std::string>& syncMethodList,
894 const std::vector<std::string>& asyncMethodList)
895 {
896 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
897 if (!nweb_ptr) {
898 WVLOG_E("WebviewController::RegisterJavaScriptProxy nweb_ptr is null");
899 return;
900 }
901 JavaScriptOb::ObjectID objId =
902 static_cast<JavaScriptOb::ObjectID>(JavaScriptOb::JavaScriptObjIdErrorCode::WEBCONTROLLERERROR);
903
904 if (!javaScriptResultCb_) {
905 WVLOG_E("WebviewController::RegisterJavaScriptProxy javaScriptResultCb_ is "
906 "null");
907 return;
908 }
909
910 if (syncMethodList.empty() && asyncMethodList.empty()) {
911 WVLOG_E("WebviewController::RegisterJavaScriptProxy all methodList are "
912 "empty");
913 return;
914 }
915
916 std::vector<std::string> allMethodList;
917 std::merge(syncMethodList.begin(), syncMethodList.end(),
918 asyncMethodList.begin(), asyncMethodList.end(),
919 std::back_inserter(allMethodList));
920 objId = javaScriptResultCb_->RegisterJavaScriptProxy(env, obj, objName, allMethodList, asyncMethodList);
921
922 nweb_ptr->RegisterArkJSfunction(objName, syncMethodList, objId);
923 }
924
RunJavaScriptCallback(const std::string & script,napi_env env,napi_ref jsCallback,bool extention)925 void WebviewController::RunJavaScriptCallback(
926 const std::string& script, napi_env env, napi_ref jsCallback, bool extention)
927 {
928 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
929 if (!nweb_ptr) {
930 napi_value setResult[RESULT_COUNT] = {0};
931 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
932 napi_get_null(env, &setResult[PARAMONE]);
933
934 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
935 napi_value callback = nullptr;
936 napi_get_reference_value(env, jsCallback, &callback);
937 napi_value callbackResult = nullptr;
938 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
939 napi_delete_reference(env, jsCallback);
940 return;
941 }
942
943 if (jsCallback == nullptr) {
944 return;
945 }
946
947 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
948 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
949 }
950
RunJavaScriptPromise(const std::string & script,napi_env env,napi_deferred deferred,bool extention)951 void WebviewController::RunJavaScriptPromise(const std::string &script, napi_env env,
952 napi_deferred deferred, bool extention)
953 {
954 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
955 if (!nweb_ptr) {
956 napi_value jsResult = nullptr;
957 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
958 napi_reject_deferred(env, deferred, jsResult);
959 return;
960 }
961
962 if (deferred == nullptr) {
963 return;
964 }
965
966 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
967 nweb_ptr->ExecuteJavaScript(script, callbackImpl, extention);
968 }
969
RunJavaScriptCallbackExt(const int fd,const size_t scriptLength,napi_env env,napi_ref jsCallback,bool extention)970 void WebviewController::RunJavaScriptCallbackExt(
971 const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention)
972 {
973 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
974 if (!nweb_ptr) {
975 napi_value setResult[RESULT_COUNT] = {0};
976 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
977 napi_get_null(env, &setResult[PARAMONE]);
978
979 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
980 napi_value callback = nullptr;
981 napi_get_reference_value(env, jsCallback, &callback);
982 napi_value callbackResult = nullptr;
983 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
984 napi_delete_reference(env, jsCallback);
985 close(fd);
986 return;
987 }
988
989 if (jsCallback == nullptr) {
990 close(fd);
991 return;
992 }
993
994 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, jsCallback, nullptr, extention);
995 nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
996 }
997
RunJavaScriptPromiseExt(const int fd,const size_t scriptLength,napi_env env,napi_deferred deferred,bool extention)998 void WebviewController::RunJavaScriptPromiseExt(
999 const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention)
1000 {
1001 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1002 if (!nweb_ptr) {
1003 napi_value jsResult = nullptr;
1004 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1005 napi_reject_deferred(env, deferred, jsResult);
1006 close(fd);
1007 return;
1008 }
1009
1010 if (deferred == nullptr) {
1011 close(fd);
1012 return;
1013 }
1014
1015 auto callbackImpl = std::make_shared<WebviewJavaScriptExecuteCallback>(env, nullptr, deferred, extention);
1016 nweb_ptr->ExecuteJavaScriptExt(fd, scriptLength, callbackImpl, extention);
1017 }
1018
GetUrl()1019 std::string WebviewController::GetUrl()
1020 {
1021 std::string url = "";
1022 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1023 if (nweb_ptr) {
1024 url = nweb_ptr->GetUrl();
1025 }
1026 return url;
1027 }
1028
GetOriginalUrl()1029 std::string WebviewController::GetOriginalUrl()
1030 {
1031 std::string url = "";
1032 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1033 if (nweb_ptr) {
1034 url = nweb_ptr->GetOriginalUrl();
1035 }
1036 return url;
1037 }
1038
TerminateRenderProcess()1039 bool WebviewController::TerminateRenderProcess()
1040 {
1041 bool ret = false;
1042 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1043 if (nweb_ptr) {
1044 ret = nweb_ptr->TerminateRenderProcess();
1045 }
1046 return ret;
1047 }
1048
PutNetworkAvailable(bool available)1049 void WebviewController::PutNetworkAvailable(bool available)
1050 {
1051 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1052 if (nweb_ptr) {
1053 nweb_ptr->PutNetworkAvailable(available);
1054 }
1055 }
1056
HasImagesCallback(napi_env env,napi_ref jsCallback)1057 ErrCode WebviewController::HasImagesCallback(napi_env env, napi_ref jsCallback)
1058 {
1059 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1060 if (!nweb_ptr) {
1061 napi_value setResult[RESULT_COUNT] = {0};
1062 setResult[PARAMZERO] = BusinessError::CreateError(env, NWebError::INIT_ERROR);
1063 napi_get_null(env, &setResult[PARAMONE]);
1064
1065 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO], setResult[PARAMONE]};
1066 napi_value callback = nullptr;
1067 napi_get_reference_value(env, jsCallback, &callback);
1068 napi_value callbackResult = nullptr;
1069 napi_call_function(env, nullptr, callback, RESULT_COUNT, args, &callbackResult);
1070 napi_delete_reference(env, jsCallback);
1071 return NWebError::INIT_ERROR;
1072 }
1073
1074 if (jsCallback == nullptr) {
1075 return NWebError::PARAM_CHECK_ERROR;
1076 }
1077
1078 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, jsCallback, nullptr);
1079 nweb_ptr->HasImages(callbackImpl);
1080 return NWebError::NO_ERROR;
1081 }
1082
HasImagesPromise(napi_env env,napi_deferred deferred)1083 ErrCode WebviewController::HasImagesPromise(napi_env env, napi_deferred deferred)
1084 {
1085 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1086 if (!nweb_ptr) {
1087 napi_value jsResult = nullptr;
1088 jsResult = NWebError::BusinessError::CreateError(env, NWebError::INIT_ERROR);
1089 napi_reject_deferred(env, deferred, jsResult);
1090 return NWebError::INIT_ERROR;
1091 }
1092
1093 if (deferred == nullptr) {
1094 return NWebError::PARAM_CHECK_ERROR;
1095 }
1096
1097 auto callbackImpl = std::make_shared<WebviewHasImageCallback>(env, nullptr, deferred);
1098 nweb_ptr->HasImages(callbackImpl);
1099 return NWebError::NO_ERROR;
1100 }
1101
RemoveCache(bool includeDiskFiles)1102 void WebviewController::RemoveCache(bool includeDiskFiles)
1103 {
1104 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1105 if (nweb_ptr) {
1106 nweb_ptr->RemoveCache(includeDiskFiles);
1107 }
1108 }
1109
GetHistoryList()1110 std::shared_ptr<NWebHistoryList> WebviewController::GetHistoryList()
1111 {
1112 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1113 if (!nweb_ptr) {
1114 return nullptr;
1115 }
1116 return nweb_ptr->GetHistoryList();
1117 }
1118
GetItem(int32_t index)1119 std::shared_ptr<NWebHistoryItem> WebHistoryList::GetItem(int32_t index)
1120 {
1121 if (!sptrHistoryList_) {
1122 return nullptr;
1123 }
1124 return sptrHistoryList_->GetItem(index);
1125 }
1126
GetListSize()1127 int32_t WebHistoryList::GetListSize()
1128 {
1129 int32_t listSize = 0;
1130
1131 if (!sptrHistoryList_) {
1132 return listSize;
1133 }
1134 listSize = sptrHistoryList_->GetListSize();
1135 return listSize;
1136 }
1137
GetFavicon(const void ** data,size_t & width,size_t & height,ImageColorType & colorType,ImageAlphaType & alphaType)1138 bool WebviewController::GetFavicon(
1139 const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType)
1140 {
1141 bool isGetFavicon = false;
1142 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1143 if (nweb_ptr) {
1144 isGetFavicon = nweb_ptr->GetFavicon(data, width, height, colorType, alphaType);
1145 }
1146 return isGetFavicon;
1147 }
1148
SerializeWebState()1149 std::vector<uint8_t> WebviewController::SerializeWebState()
1150 {
1151 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1152 if (nweb_ptr) {
1153 return nweb_ptr->SerializeWebState();
1154 }
1155 std::vector<uint8_t> empty;
1156 return empty;
1157 }
1158
RestoreWebState(const std::vector<uint8_t> & state)1159 bool WebviewController::RestoreWebState(const std::vector<uint8_t> &state)
1160 {
1161 bool isRestored = false;
1162 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1163 if (nweb_ptr) {
1164 isRestored = nweb_ptr->RestoreWebState(state);
1165 }
1166 return isRestored;
1167 }
1168
ScrollPageDown(bool bottom)1169 void WebviewController::ScrollPageDown(bool bottom)
1170 {
1171 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1172 if (nweb_ptr) {
1173 nweb_ptr->PageDown(bottom);
1174 }
1175 return;
1176 }
1177
ScrollPageUp(bool top)1178 void WebviewController::ScrollPageUp(bool top)
1179 {
1180 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1181 if (nweb_ptr) {
1182 nweb_ptr->PageUp(top);
1183 }
1184 return;
1185 }
1186
ScrollTo(float x,float y)1187 void WebviewController::ScrollTo(float x, float y)
1188 {
1189 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1190 if (nweb_ptr) {
1191 nweb_ptr->ScrollTo(x, y);
1192 }
1193 return;
1194 }
1195
ScrollBy(float deltaX,float deltaY)1196 void WebviewController::ScrollBy(float deltaX, float deltaY)
1197 {
1198 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1199 if (nweb_ptr) {
1200 nweb_ptr->ScrollBy(deltaX, deltaY);
1201 }
1202 return;
1203 }
1204
SlideScroll(float vx,float vy)1205 void WebviewController::SlideScroll(float vx, float vy)
1206 {
1207 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1208 if (nweb_ptr) {
1209 nweb_ptr->SlideScroll(vx, vy);
1210 }
1211 return;
1212 }
1213
SetScrollable(bool enable)1214 void WebviewController::SetScrollable(bool enable)
1215 {
1216 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1217 if (!nweb_ptr) {
1218 return;
1219 }
1220 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1221 if (!setting) {
1222 return;
1223 }
1224 return setting->SetScrollable(enable);
1225 }
1226
GetScrollable()1227 bool WebviewController::GetScrollable()
1228 {
1229 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1230 if (!nweb_ptr) {
1231 return true;
1232 }
1233 std::shared_ptr<OHOS::NWeb::NWebPreference> setting = nweb_ptr->GetPreference();
1234 if (!setting) {
1235 return true;
1236 }
1237 return setting->GetScrollable();
1238 }
1239
InnerSetHapPath(const std::string & hapPath)1240 void WebviewController::InnerSetHapPath(const std::string &hapPath)
1241 {
1242 hapPath_ = hapPath;
1243 }
1244
GetCertChainDerData(std::vector<std::string> & certChainDerData)1245 bool WebviewController::GetCertChainDerData(std::vector<std::string> &certChainDerData)
1246 {
1247 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1248 if (!nweb_ptr) {
1249 WVLOG_E("GetCertChainDerData failed, nweb ptr is null");
1250 return false;
1251 }
1252
1253 return nweb_ptr->GetCertChainDerData(certChainDerData, true);
1254 }
1255
SetAudioMuted(bool muted)1256 ErrCode WebviewController::SetAudioMuted(bool muted)
1257 {
1258 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1259 if (!nweb_ptr) {
1260 return NWebError::INIT_ERROR;
1261 }
1262
1263 nweb_ptr->SetAudioMuted(muted);
1264 return NWebError::NO_ERROR;
1265 }
1266
PrefetchPage(std::string & url,std::map<std::string,std::string> additionalHttpHeaders)1267 ErrCode WebviewController::PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders)
1268 {
1269 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1270 if (!nweb_ptr) {
1271 return NWebError::INIT_ERROR;
1272 }
1273
1274 nweb_ptr->PrefetchPage(url, additionalHttpHeaders);
1275 return NWebError::NO_ERROR;
1276 }
1277
OnStartLayoutWrite(const std::string & jobId,const PrintAttributesAdapter & oldAttrs,const PrintAttributesAdapter & newAttrs,uint32_t fd,std::function<void (std::string,uint32_t)> writeResultCallback)1278 void WebPrintDocument::OnStartLayoutWrite(const std::string& jobId, const PrintAttributesAdapter& oldAttrs,
1279 const PrintAttributesAdapter& newAttrs, uint32_t fd, std::function<void(std::string, uint32_t)> writeResultCallback)
1280 {
1281 if (printDocAdapter_) {
1282 std::shared_ptr<PrintWriteResultCallbackAdapter> callback =
1283 std::make_shared<WebPrintWriteResultCallbackAdapter>(writeResultCallback);
1284 printDocAdapter_->OnStartLayoutWrite(jobId, oldAttrs, newAttrs, fd, callback);
1285 }
1286 }
1287
OnJobStateChanged(const std::string & jobId,uint32_t state)1288 void WebPrintDocument::OnJobStateChanged(const std::string& jobId, uint32_t state)
1289 {
1290 if (printDocAdapter_) {
1291 printDocAdapter_->OnJobStateChanged(jobId, state);
1292 }
1293 }
1294
CreateWebPrintDocumentAdapter(const std::string & jobName)1295 void* WebviewController::CreateWebPrintDocumentAdapter(const std::string& jobName)
1296 {
1297 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1298 if (!nweb_ptr) {
1299 return nullptr;
1300 }
1301 return nweb_ptr->CreateWebPrintDocumentAdapter(jobName);
1302 }
1303
CloseAllMediaPresentations()1304 void WebviewController::CloseAllMediaPresentations()
1305 {
1306 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1307 if (nweb_ptr) {
1308 nweb_ptr->CloseAllMediaPresentations();
1309 }
1310 }
1311
StopAllMedia()1312 void WebviewController::StopAllMedia()
1313 {
1314 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1315 if (nweb_ptr) {
1316 nweb_ptr->StopAllMedia();
1317 }
1318 }
1319
ResumeAllMedia()1320 void WebviewController::ResumeAllMedia()
1321 {
1322 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1323 if (nweb_ptr) {
1324 nweb_ptr->ResumeAllMedia();
1325 }
1326 }
1327
PauseAllMedia()1328 void WebviewController::PauseAllMedia()
1329 {
1330 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1331 if (nweb_ptr) {
1332 nweb_ptr->PauseAllMedia();
1333 }
1334 }
1335
GetMediaPlaybackState()1336 int WebviewController::GetMediaPlaybackState()
1337 {
1338 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1339 if (!nweb_ptr) {
1340 return static_cast<int>(MediaPlaybackState::NONE);
1341 }
1342 return nweb_ptr->GetMediaPlaybackState();
1343 }
1344
GetSecurityLevel()1345 int WebviewController::GetSecurityLevel()
1346 {
1347 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1348 if (!nweb_ptr) {
1349 return static_cast<int>(SecurityLevel::NONE);
1350 }
1351
1352 int nwebSecurityLevel = nweb_ptr->GetSecurityLevel();
1353 SecurityLevel securityLevel;
1354 switch (nwebSecurityLevel) {
1355 case static_cast<int>(CoreSecurityLevel::NONE):
1356 securityLevel = SecurityLevel::NONE;
1357 break;
1358 case static_cast<int>(CoreSecurityLevel::SECURE):
1359 securityLevel = SecurityLevel::SECURE;
1360 break;
1361 case static_cast<int>(CoreSecurityLevel::WARNING):
1362 securityLevel = SecurityLevel::WARNING;
1363 break;
1364 case static_cast<int>(CoreSecurityLevel::DANGEROUS):
1365 securityLevel = SecurityLevel::DANGEROUS;
1366 break;
1367 default:
1368 securityLevel = SecurityLevel::NONE;
1369 break;
1370 }
1371
1372 return static_cast<int>(securityLevel);
1373 }
1374
IsIncognitoMode()1375 bool WebviewController::IsIncognitoMode()
1376 {
1377 bool incognitoMode = false;
1378 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1379 if (nweb_ptr) {
1380 incognitoMode = nweb_ptr->IsIncognitoMode();
1381 }
1382 return incognitoMode;
1383 }
1384
SetPrintBackground(bool enable)1385 void WebviewController::SetPrintBackground(bool enable)
1386 {
1387 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1388 if (nweb_ptr) {
1389 nweb_ptr->SetPrintBackground(enable);
1390 }
1391 }
1392
GetPrintBackground()1393 bool WebviewController::GetPrintBackground()
1394 {
1395 bool printBackgroundEnabled = false;
1396 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1397 if (nweb_ptr) {
1398 printBackgroundEnabled = nweb_ptr->GetPrintBackground();
1399 }
1400
1401 return printBackgroundEnabled;
1402 }
1403
EnableIntelligentTrackingPrevention(bool enable)1404 void WebviewController::EnableIntelligentTrackingPrevention(bool enable)
1405 {
1406 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1407 if (nweb_ptr) {
1408 nweb_ptr->EnableIntelligentTrackingPrevention(enable);
1409 }
1410 }
1411
IsIntelligentTrackingPreventionEnabled()1412 bool WebviewController::IsIntelligentTrackingPreventionEnabled()
1413 {
1414 bool enabled = false;
1415 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1416 if (nweb_ptr) {
1417 enabled = nweb_ptr->IsIntelligentTrackingPreventionEnabled();
1418 }
1419 return enabled;
1420 }
1421
WriteResultCallback(std::string jobId,uint32_t code)1422 void WebPrintWriteResultCallbackAdapter::WriteResultCallback(std::string jobId, uint32_t code)
1423 {
1424 cb_(jobId, code);
1425 }
1426
SetWebSchemeHandler(const char * scheme,WebSchemeHandler * handler)1427 bool WebviewController::SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler)
1428 {
1429 if (!handler || !scheme) {
1430 WVLOG_E("WebviewController::SetWebSchemeHandler handler or scheme is nullptr");
1431 return false;
1432 }
1433 ArkWeb_SchemeHandler* schemeHandler =
1434 const_cast<ArkWeb_SchemeHandler*>(WebSchemeHandler::GetArkWebSchemeHandler(handler));
1435 return OH_ArkWeb_SetSchemeHandler(scheme, webTag_.c_str(), schemeHandler);
1436 }
1437
ClearWebSchemeHandler()1438 int32_t WebviewController::ClearWebSchemeHandler()
1439 {
1440 return OH_ArkWeb_ClearSchemeHandlers(webTag_.c_str());
1441 }
1442
SetWebServiveWorkerSchemeHandler(const char * scheme,WebSchemeHandler * handler)1443 bool WebviewController::SetWebServiveWorkerSchemeHandler(
1444 const char* scheme, WebSchemeHandler* handler)
1445 {
1446 ArkWeb_SchemeHandler* schemeHandler =
1447 const_cast<ArkWeb_SchemeHandler*>(WebSchemeHandler::GetArkWebSchemeHandler(handler));
1448 return OH_ArkWebServiceWorker_SetSchemeHandler(scheme, schemeHandler);
1449 }
1450
ClearWebServiceWorkerSchemeHandler()1451 int32_t WebviewController::ClearWebServiceWorkerSchemeHandler()
1452 {
1453 return OH_ArkWebServiceWorker_ClearSchemeHandlers();
1454 }
1455
StartCamera()1456 ErrCode WebviewController::StartCamera()
1457 {
1458 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1459 if (!nweb_ptr) {
1460 return NWebError::INIT_ERROR;
1461 }
1462
1463 nweb_ptr->StartCamera();
1464 return NWebError::NO_ERROR;
1465 }
1466
StopCamera()1467 ErrCode WebviewController::StopCamera()
1468 {
1469 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1470 if (!nweb_ptr) {
1471 return NWebError::INIT_ERROR;
1472 }
1473
1474 nweb_ptr->StopCamera();
1475 return NWebError::NO_ERROR;
1476 }
1477
CloseCamera()1478 ErrCode WebviewController::CloseCamera()
1479 {
1480 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1481 if (!nweb_ptr) {
1482 return NWebError::INIT_ERROR;
1483 }
1484
1485 nweb_ptr->CloseCamera();
1486 return NWebError::NO_ERROR;
1487 }
1488
GetLastJavascriptProxyCallingFrameUrl()1489 std::string WebviewController::GetLastJavascriptProxyCallingFrameUrl()
1490 {
1491 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1492 if (!nweb_ptr) {
1493 return "";
1494 }
1495
1496 return nweb_ptr->GetLastJavascriptProxyCallingFrameUrl();
1497 }
1498
OnCreateNativeMediaPlayer(napi_env env,napi_ref callback)1499 void WebviewController::OnCreateNativeMediaPlayer(napi_env env, napi_ref callback)
1500 {
1501 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1502 if (!nweb_ptr) {
1503 return;
1504 }
1505
1506 auto callbackImpl = std::make_shared<NWebCreateNativeMediaPlayerCallbackImpl>(nwebId_, env, callback);
1507 nweb_ptr->OnCreateNativeMediaPlayer(callbackImpl);
1508 }
1509
ParseScriptContent(napi_env env,napi_value value,std::string & script)1510 bool WebviewController::ParseScriptContent(napi_env env, napi_value value, std::string &script)
1511 {
1512 napi_valuetype valueType;
1513 napi_typeof(env, value, &valueType);
1514 if (valueType == napi_string) {
1515 std::string str;
1516 if (!NapiParseUtils::ParseString(env, value, str)) {
1517 WVLOG_E("PrecompileJavaScript: parse script text to string failed.");
1518 return false;
1519 }
1520
1521 script = str;
1522 return true;
1523 }
1524
1525 std::vector<uint8_t> vec = ParseUint8Array(env, value);
1526 if (!vec.size()) {
1527 WVLOG_E("PrecompileJavaScript: parse script text to Uint8Array failed.");
1528 return false;
1529 }
1530
1531 std::string str(vec.begin(), vec.end());
1532 script = str;
1533 return true;
1534 }
1535
ParseCacheOptions(napi_env env,napi_value value)1536 std::shared_ptr<CacheOptions> WebviewController::ParseCacheOptions(napi_env env, napi_value value) {
1537 std::map<std::string, std::string> responseHeaders;
1538 bool isModule = false;
1539 bool isTopLevel = false;
1540 auto defaultCacheOptions = std::make_shared<NWebCacheOptionsImpl>(responseHeaders, isModule, isTopLevel);
1541
1542 napi_value responseHeadersValue = nullptr;
1543 if (napi_get_named_property(env, value, "responseHeaders", &responseHeadersValue) != napi_ok) {
1544 WVLOG_D("PrecompileJavaScript: cannot get 'responseHeaders' of CacheOptions.");
1545 return defaultCacheOptions;
1546 }
1547
1548 if (!ParseResponseHeaders(env, responseHeadersValue, responseHeaders)) {
1549 WVLOG_D("PrecompileJavaScript: parse 'responseHeaders' of CacheOptions failed. use default options");
1550 return defaultCacheOptions;
1551 }
1552
1553 return std::make_shared<NWebCacheOptionsImpl>(responseHeaders, isModule, isTopLevel);
1554 }
1555
PrecompileJavaScriptPromise(napi_env env,napi_deferred deferred,const std::string & url,const std::string & script,std::shared_ptr<CacheOptions> cacheOptions)1556 ErrCode WebviewController::PrecompileJavaScriptPromise(
1557 napi_env env, napi_deferred deferred,
1558 const std::string &url, const std::string &script, std::shared_ptr<CacheOptions> cacheOptions)
1559 {
1560 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1561 if (!nweb_ptr) {
1562 return NWebError::INIT_ERROR;
1563 }
1564
1565 if (!deferred) {
1566 return NWebError::INIT_ERROR;
1567 }
1568
1569 auto callbackImpl = std::make_shared<OHOS::NWeb::NWebPrecompileCallback>();
1570 callbackImpl->SetCallback([env, deferred](int64_t result) {
1571 if (!env) {
1572 return;
1573 }
1574
1575 napi_handle_scope scope = nullptr;
1576 napi_open_handle_scope(env, &scope);
1577 if (scope == nullptr) {
1578 return;
1579 }
1580
1581 napi_value setResult[RESULT_COUNT] = {0};
1582 napi_create_int64(env, result, &setResult[PARAMZERO]);
1583 napi_value args[RESULT_COUNT] = {setResult[PARAMZERO]};
1584 if (result == static_cast<int64_t>(PrecompileError::OK)) {
1585 napi_resolve_deferred(env, deferred, args[PARAMZERO]);
1586 } else {
1587 napi_reject_deferred(env, deferred, args[PARAMZERO]);
1588 }
1589
1590 napi_close_handle_scope(env, scope);
1591 });
1592
1593 nweb_ptr->PrecompileJavaScript(url, script, cacheOptions, callbackImpl);
1594 return NWebError::NO_ERROR;
1595 }
1596
ParseResponseHeaders(napi_env env,napi_value value,std::map<std::string,std::string> & responseHeaders)1597 bool WebviewController::ParseResponseHeaders(napi_env env,
1598 napi_value value,
1599 std::map<std::string, std::string> &responseHeaders)
1600 {
1601 bool isArray = false;
1602 napi_is_array(env, value, &isArray);
1603 if (!isArray) {
1604 WVLOG_E("Response headers is not array.");
1605 return false;
1606 }
1607
1608 uint32_t length = INTEGER_ZERO;
1609 napi_get_array_length(env, value, &length);
1610 for (uint32_t i = 0; i < length; i++) {
1611 std::string keyString;
1612 std::string valueString;
1613 napi_value header = nullptr;
1614 napi_value keyObj = nullptr;
1615 napi_value valueObj = nullptr;
1616 napi_get_element(env, value, i, &header);
1617
1618 if (napi_get_named_property(env, header, "headerKey", &keyObj) != napi_ok ||
1619 !NapiParseUtils::ParseString(env, keyObj, keyString)) {
1620 continue;
1621 }
1622
1623 if (napi_get_named_property(env, header, "headerValue", &valueObj) != napi_ok ||
1624 !NapiParseUtils::ParseString(env, valueObj, valueString)) {
1625 continue;
1626 }
1627
1628 responseHeaders[keyString] = valueString;
1629 }
1630
1631 return true;
1632 }
1633
ParseURLList(napi_env env,napi_value value,std::vector<std::string> & urlList)1634 ParseURLResult WebviewController::ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList)
1635 {
1636 if (!NapiParseUtils::ParseStringArray(env, value, urlList)) {
1637 return ParseURLResult::FAILED;
1638 }
1639
1640 for (auto url : urlList) {
1641 if (!CheckURL(url)) {
1642 return ParseURLResult::INVALID_URL;
1643 }
1644 }
1645
1646 return ParseURLResult::OK;
1647 }
1648
CheckURL(std::string & url)1649 bool WebviewController::CheckURL(std::string& url)
1650 {
1651 if (url.size() > URL_MAXIMUM) {
1652 WVLOG_E("The URL exceeds the maximum length of %{public}d. URL: %{public}s", URL_MAXIMUM, url.c_str());
1653 return false;
1654 }
1655
1656 if (!regex_match(url, std::regex("^http(s)?:\\/\\/.+", std::regex_constants::icase))) {
1657 WVLOG_E("The Parse URL error. URL: %{public}s", url.c_str());
1658 return false;
1659 }
1660
1661 return true;
1662 }
1663
ParseUint8Array(napi_env env,napi_value value)1664 std::vector<uint8_t> WebviewController::ParseUint8Array(napi_env env, napi_value value)
1665 {
1666 napi_typedarray_type typedArrayType;
1667 size_t length = 0;
1668 napi_value buffer = nullptr;
1669 size_t offset = 0;
1670 napi_get_typedarray_info(env, value, &typedArrayType, &length, nullptr, &buffer, &offset);
1671 if (typedArrayType != napi_uint8_array) {
1672 WVLOG_E("Param is not Unit8Array.");
1673 return std::vector<uint8_t>();
1674 }
1675
1676 uint8_t *data = nullptr;
1677 size_t total = 0;
1678 napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total);
1679 length = std::min<size_t>(length, total - offset);
1680 std::vector<uint8_t> vec(length);
1681 int retCode = memcpy_s(vec.data(), vec.size(), &data[offset], length);
1682 if (retCode != 0) {
1683 WVLOG_E("Parse Uint8Array failed.");
1684 return std::vector<uint8_t>();
1685 }
1686
1687 return vec;
1688 }
1689
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)1690 void WebviewController::InjectOfflineResource(const std::vector<std::string>& urlList,
1691 const std::vector<uint8_t>& resource,
1692 const std::map<std::string, std::string>& response_headers,
1693 const uint32_t type)
1694 {
1695 auto nweb_ptr = NWebHelper::Instance().GetNWeb(nwebId_);
1696 if (!nweb_ptr) {
1697 return;
1698 }
1699
1700 std::string originUrl = urlList[0];
1701 if (urlList.size() == 1) {
1702 nweb_ptr->InjectOfflineResource(originUrl, originUrl, resource, response_headers, type);
1703 return;
1704 }
1705
1706 for (size_t i = 1 ; i < urlList.size() ; i++) {
1707 nweb_ptr->InjectOfflineResource(urlList[i], originUrl, resource, response_headers, type);
1708 }
1709 }
1710 } // namespace NWeb
1711 } // namespace OHOS
1712