• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 #ifndef NWEB_WEBVIEW_CONTROLLER_H
17 #define NWEB_WEBVIEW_CONTROLLER_H
18 
19 #include <filesystem>
20 #include <memory>
21 #include <string>
22 #include <unordered_map>
23 
24 #include "auto_napi_ref.h"
25 #include "napi/native_api.h"
26 #include "napi/native_common.h"
27 #include "napi/native_node_api.h"
28 #include "nweb.h"
29 #include "nweb_helper.h"
30 #include "nweb_web_message.h"
31 #include "web_errors.h"
32 #include "webview_javascript_result_callback.h"
33 #include "webview_controller_print_structs.h"
34 
35 #include "web_scheme_handler_request.h"
36 #include "webview_value.h"
37 
38 namespace OHOS {
39 namespace NWeb {
40 enum class WebHitTestType : int {
41     EDIT = 0,
42     EMAIL,
43     HTTP,
44     HTTP_IMG,
45     IMG,
46     MAP,
47     PHONE,
48     UNKNOWN
49 };
50 
51 enum class SecureDnsModeType : int {
52     OFF = 0,
53     AUTO,
54     SECURE_ONLY
55 };
56 
57 enum class ResourceType : uint32_t {
58     COLOR = 10001,
59     FLOAT,
60     STRING,
61     PLURAL,
62     BOOLEAN,
63     INTARRAY,
64     INTEGER,
65     PATTERN,
66     STRARRAY,
67     MEDIA = 20000,
68     RAWFILE = 30000
69 };
70 
71 enum class WebMessageType : int {
72     NOTSUPPORT = 0,
73     STRING,
74     NUMBER,
75     BOOLEAN,
76     ARRAYBUFFER,
77     ARRAY,
78     ERROR
79 };
80 
81 enum class MediaPlaybackState : int {
82     NONE = 0,
83     PLAYING,
84     PAUSED,
85     STOP
86 };
87 
88 enum class SecurityLevel : int {
89     NONE = 0,
90     SECURE,
91     WARNING,
92     DANGEROUS
93 };
94 
95 enum class CoreSecurityLevel : int {
96     NONE = 0,
97     SECURE = 3,
98     WARNING = 6,
99     DANGEROUS = 5
100 };
101 
102 enum class OfflineResourceType : int {
103     IMAGE = 0,
104     CSS,
105     CLASSIC_JS,
106     MODULE_JS
107 };
108 
109 enum class ParseURLResult : int {
110     OK = 0,
111     FAILED,
112     INVALID_URL
113 };
114 
115 enum class UrlListSetResult : int {
116     INIT_ERROR = -2,
117     PARAM_ERROR = -1,
118     SET_OK = 0,
119 };
120 
121 enum class ScrollType : int {
122     EVENT = 0,
123 };
124 
125 enum class PressureLevel : int {
126     MEMORY_PRESSURE_LEVEL_MODERATE = 1,
127     MEMORY_PRESSURE_LEVEL_CRITICAL = 2,
128 };
129 
130 enum class AttachState : int {
131     NOT_ATTACHED = 0,
132     ATTACHED = 1
133 };
134 
135 enum class BlanklessErrorCode : int {
136     SUCCESS = 0,
137     ERR_UNKNOWN = -1,
138     ERR_INVALID_PARAM = -2,
139     ERR_CONTROLLER_NOT_INITED = -3,
140     ERR_KEY_NOT_MATCH = -4,
141     ERR_SIGNIFICANT_CHANGE = -5
142 };
143 
144 class WebRegObj {
145 public:
WebRegObj()146     WebRegObj() : m_regEnv(0), m_regHanderRef(nullptr) {
147     }
148 
WebRegObj(const napi_env & env,const napi_ref & ref)149     explicit WebRegObj(const napi_env& env, const napi_ref& ref)
150     {
151         m_regEnv = env;
152         m_regHanderRef = ref;
153         m_isMarked = false;
154     }
155 
~WebRegObj()156     ~WebRegObj() {
157     }
158 
159     napi_env m_regEnv;
160     napi_ref m_regHanderRef;
161     bool m_isMarked;
162 };
163 
164 class WebPrintDocument;
165 class WebviewController {
166 public:
167     explicit WebviewController() = default;
168     explicit WebviewController(int32_t nwebId);
169     explicit WebviewController(const std::string& webTag);
170     ~WebviewController();
171 
172     bool IsInit() const;
173 
174     void SetWebId(int32_t nwebId);
175 
176     WebviewController* FromID(int32_t nwebId);
177 
178     bool AccessForward() const;
179 
180     bool AccessBackward() const;
181 
182     bool AccessStep(int32_t step) const;
183 
184     void ClearHistory();
185 
186     void Forward();
187 
188     void Backward();
189 
190     void OnActive();
191 
192     void OnInactive();
193 
194     void Refresh();
195 
196     ErrCode ZoomIn();
197 
198     ErrCode ZoomOut();
199 
200     int32_t GetWebId() const;
201 
202     std::string GetUserAgent();
203 
204     std::string GetCustomUserAgent() const;
205 
206     ErrCode SetCustomUserAgent(const std::string& userAgent);
207 
208     std::string GetTitle();
209 
210     int32_t GetProgress();
211 
212     int32_t GetPageHeight();
213 
214     ErrCode BackOrForward(int32_t step);
215 
216     void StoreWebArchiveCallback(const std::string &baseName, bool autoName, napi_env env, napi_ref jsCallback);
217 
218     void StoreWebArchivePromise(const std::string &baseName, bool autoName, napi_env env, napi_deferred deferred);
219 
220     std::vector<std::string> CreateWebMessagePorts();
221 
222     ErrCode PostWebMessage(std::string& message, std::vector<std::string>& ports, std::string& targetUrl);
223 
224     std::shared_ptr<HitTestResult> GetHitTestValue();
225 
226     void RequestFocus();
227 
228     bool ParseUrl(napi_env env, napi_value urlObj, std::string& result) const;
229 
230     ErrCode LoadUrl(std::string url);
231 
232     ErrCode LoadUrl(std::string url, std::map<std::string, std::string> httpHeaders);
233 
234     ErrCode LoadData(std::string data, std::string mimeType, std::string encoding,
235         std::string baseUrl, std::string historyUrl);
236 
237     int GetHitTest();
238 
239     void ClearMatches();
240 
241     void SearchNext(bool forward);
242 
243     void SearchAllAsync(const std::string& searchString);
244 
245     void ClearSslCache();
246 
247     void ClearClientAuthenticationCache();
248 
249     void Stop();
250 
251     ErrCode Zoom(float factor);
252 
253     void InnerCompleteWindowNew(int32_t parentNwebId);
254 
255     void SetNWebJavaScriptResultCallBack();
256 
257     void RegisterJavaScriptProxy(RegisterJavaScriptProxyParam& param);
258 
259     ErrCode DeleteJavaScriptRegister(const std::string& objName,
260         const std::vector<std::string>& methodList);
261 
262     void RunJavaScriptCallback(const std::string &script, napi_env env, napi_ref jsCallback, bool extention);
263 
264     void RunJavaScriptPromise(const std::string &script, napi_env env, napi_deferred deferred, bool extention);
265 
266     void RunJavaScriptCallbackExt(
267         const int fd, const size_t scriptLength, napi_env env, napi_ref jsCallback, bool extention);
268 
269     void RunJavaScriptPromiseExt(
270         const int fd, const size_t scriptLength, napi_env env, napi_deferred deferred, bool extention);
271 
272     std::string GetUrl();
273 
274     std::string GetOriginalUrl();
275 
276     bool TerminateRenderProcess() const;
277 
278     void PutNetworkAvailable(bool available);
279 
280     bool HasImage(std::shared_ptr<NWebBoolValueCallback> callback);
281 
282     ErrCode HasImagesCallback(napi_env env, napi_ref jsCallback);
283 
284     ErrCode HasImagesPromise(napi_env env, napi_deferred deferred);
285 
286     void RemoveCache(bool includeDiskFiles);
287 
288     std::shared_ptr<NWebHistoryList> GetHistoryList();
289 
290     bool GetFavicon(
291         const void **data, size_t &width, size_t &height, ImageColorType &colorType, ImageAlphaType &alphaType) const;
292 
293     std::vector<uint8_t> SerializeWebState();
294 
295     bool RestoreWebState(const std::vector<uint8_t> &state) const;
296 
297     void ScrollPageDown(bool bottom);
298 
299     void ScrollPageUp(bool top);
300 
301     void ScrollTo(float x, float y);
302 
303     void ScrollBy(float deltaX, float deltaY);
304 
305     void SlideScroll(float vx, float vy);
306 
307     void SetScrollable(bool enable);
308 
309     void SetScrollable(bool enable, int32_t scrollType);
310 
311     bool GetScrollable() const;
312 
313     void InnerSetHapPath(const std::string &hapPath);
314 
315     void InnerSetFavicon(napi_env env, napi_value favicon);
316 
317     napi_value InnerGetFavicon(napi_env env);
318 
319     bool GetCertChainDerData(std::vector<std::string> &certChainDerData) const;
320 
321     ErrCode SetAudioMuted(bool muted);
322 
323     ErrCode PrefetchPage(std::string& url, std::map<std::string, std::string> additionalHttpHeaders);
324 
325     void* CreateWebPrintDocumentAdapter(const std::string &jobName, int32_t& useAdapterV2);
326 
327     ErrCode PostUrl(std::string& url, std::vector<char>& postData);
328 
329     void EnableSafeBrowsing(bool enable);
330 
331     bool IsSafeBrowsingEnabled() const;
332 
333     int GetSecurityLevel();
334 
335     bool IsIncognitoMode() const;
336 
337     void SetPrintBackground(bool enable);
338 
339     bool GetPrintBackground() const;
340 
341     static std::string GenerateWebTag();
342 
343     bool SetWebSchemeHandler(const char* scheme, WebSchemeHandler* handler) const;
344 
345     int32_t ClearWebSchemeHandler();
346 
347     static bool SetWebServiveWorkerSchemeHandler(
348         const char* scheme, WebSchemeHandler* handler);
349 
350     static int32_t ClearWebServiceWorkerSchemeHandler();
351 
352     std::string GetLastJavascriptProxyCallingFrameUrl();
353 
354     void EnableIntelligentTrackingPrevention(bool enable);
355 
356     bool IsIntelligentTrackingPreventionEnabled() const;
357 
358     ErrCode StartCamera();
359 
360     ErrCode StopCamera();
361 
362     ErrCode CloseCamera();
363 
364     void CloseAllMediaPresentations();
365 
366     void StopAllMedia();
367 
368     void ResumeAllMedia();
369 
370     void PauseAllMedia();
371 
372     int GetMediaPlaybackState();
373 
374     void OnCreateNativeMediaPlayer(napi_env env, napi_ref callback);
375 
376     bool ParseScriptContent(napi_env env, napi_value value, std::string &script);
377 
378     std::shared_ptr<CacheOptions> ParseCacheOptions(napi_env env, napi_value value);
379 
380     void PrecompileJavaScriptPromise(napi_env env,
381                                      napi_deferred deferred,
382                                      const std::string &url, const std::string &script,
383                                      std::shared_ptr<CacheOptions> cacheOptions);
384 
385     bool ParseResponseHeaders(napi_env env,
386                               napi_value value,
387                               std::map<std::string, std::string> &responseHeaders) const;
388 
389     ParseURLResult ParseURLList(napi_env env, napi_value value, std::vector<std::string>& urlList);
390 
391     bool CheckURL(std::string& url) const;
392 
393     std::vector<uint8_t> ParseUint8Array(napi_env env, napi_value value);
394 
395     void InjectOfflineResource(const std::vector<std::string>& urlList,
396                                const std::vector<uint8_t>& resource,
397                                const std::map<std::string, std::string>& response_headers,
398                                const uint32_t type);
399 
400     ErrCode SetUrlTrustList(const std::string& urlTrustList, std::string& detailErrMsg);
401 
402     std::string GetSurfaceId();
403     void EnableAdsBlock(bool enable);
404 
405     bool IsAdsBlockEnabled() const;
406 
407     bool IsAdsBlockEnabledForCurPage() const;
408 
409     bool ParseJsLengthToInt(napi_env env,
410                             napi_value jsLength,
411                             PixelUnit& type,
412                             int32_t& result) const;
413 
414     ErrCode WebPageSnapshot(const char* id,
415                             PixelUnit type,
416                             int32_t width,
417                             int32_t height,
418                             const WebSnapshotCallback callback);
419 
420     void UpdateInstanceId(int32_t newId);
421 
422     void SetBackForwardCacheOptions(int32_t size, int32_t timeToLive);
423 
424     void SetPathAllowingUniversalAccess(const std::vector<std::string>& pathList,
425                                         std::string& errorPath);
426 
427     bool ScrollByWithResult(float deltaX, float deltaY) const;
428 
429     void ScrollToWithAnime(float x, float y, int32_t duration) ;
430 
431     void ScrollByWithAnime(float deltaX, float deltaY, int32_t duration) ;
432 
433     void GetScrollOffset(float* offset_x, float* offset_y);
434 
435     void GetPageOffset(float* offset_x, float* offset_y);
436 
437     void CreatePDFCallbackExt(
438         napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_ref pdfCallback);
439 
440     void CreatePDFPromiseExt(
441         napi_env env, std::shared_ptr<NWebPDFConfigArgs> pdfConfig, napi_deferred deferred);
442 
443     std::shared_ptr<HitTestResult> GetLastHitTest();
444 
445     void SaveWebSchemeHandler(const char* scheme, WebSchemeHandler* handler);
446 
447     static void SaveWebServiceWorkerSchemeHandler(const char* scheme, WebSchemeHandler* handler);
448 
449     int GetAttachState();
450 
451     void RegisterStateChangeCallback(
452         const napi_env& env, const std::string& type, napi_value handler);
453 
454     void TriggerStateChangeCallback(const std::string& type);
455 
456     void DeleteRegisterObj(
457         const napi_env& env, std::vector<WebRegObj>& vecRegObjs, napi_value& handler);
458 
459     void DeleteAllRegisterObj(const napi_env& env, std::vector<WebRegObj>& vecRegObjs);
460 
461     void UnregisterStateChangeCallback(
462         const napi_env& env, const std::string& type, napi_value handler);
463 
464     static void WaitForAttached(napi_env env, void* data);
465 
466     static void TriggerWaitforAttachedPromise(napi_env env, napi_status status, void *data);
467 
468     napi_value WaitForAttachedPromise(napi_env env, int32_t timeout, napi_deferred deferred);
469 
470     int32_t GetBlanklessInfoWithKey(const std::string& key, double* similarity, int32_t* loadingTime);
471 
472     int32_t SetBlanklessLoadingWithKey(const std::string& key, bool isStart);
473 
474     void SetWebDetach(int32_t nwebId);
475 
476     ErrCode AvoidVisibleViewportBottom(int32_t avoidHeight);
477 
478     ErrCode SetErrorPageEnabled(bool enable);
479 
480     bool GetErrorPageEnabled();
481 private:
482     int ConverToWebHitTestType(int hitType);
483 
484     bool GetRawFileUrl(const std::string &fileName,
485         const std::string& bundleName, const std::string& moduleName, std::string &result) const;
486 
487     bool ParseRawFileUrl(napi_env env, napi_value urlObj, std::string& result) const;
488 
489     bool GetResourceUrl(napi_env env, napi_value urlObj, std::string& result) const;
490 
491     bool ParseJsLengthResourceToInt(napi_env env,
492                                     napi_value jsLength,
493                                     PixelUnit& type,
494                                     int32_t& result) const;
495     bool GetHapModuleInfo();
496 
497     void DeleteWebSchemeHandler();
498 
499     static void DeleteWebServiceWorkerSchemeHandler();
500 
501 public:
502     static std::string customeSchemeCmdLine_;
503     static bool existNweb_;
504     static bool webDebuggingAccess_;
505     static int32_t webDebuggingPort_;
506     static std::set<std::string> webTagSet_;
507     static int32_t webTagStrId_;
508 
509 private:
510     std::mutex webMtx_;
511     int32_t nwebId_ = -1;
512     std::shared_ptr<WebviewJavaScriptResultCallBack> javaScriptResultCb_ = nullptr;
513     std::string hapPath_ = "";
514     std::string webTag_ = "";
515     AutoNapiRef favicon_;
516     std::vector<std::string> moduleName_;
517     std::map<std::string, WebSchemeHandler*> webSchemeHandlerMap_;
518     static std::map<std::string, WebSchemeHandler*> webServiceWorkerSchemeHandlerMap_;
519     AttachState attachState_ = AttachState::NOT_ATTACHED;
520     std::unordered_map<std::string, std::vector<WebRegObj>> attachEventRegisterInfo_;
521     std::condition_variable attachCond_;
522     std::mutex attachMtx_;
523 };
524 
525 class WebMessageExt {
526 public:
527     explicit WebMessageExt(std::shared_ptr<NWebMessage> data,
528         std::shared_ptr<NWebRomValue> value = nullptr)
data_(data)529         : data_(data), value_(value) {}
530     ~WebMessageExt() = default;
531 
532     void SetType(int type);
533 
534     int ConvertNwebType2JsType(NWebValue::Type type);
535 
GetType()536     int GetType()
537     {
538         if (data_) {
539             return ConvertNwebType2JsType(data_->GetType());
540         }
541         return static_cast<int>(WebMessageType::NOTSUPPORT);
542     }
543 
SetString(std::string value)544     void SetString(std::string value)
545     {
546         if (data_) {
547             data_->SetType(NWebValue::Type::STRING);
548             data_->SetString(value);
549         }
550         if (value_) {
551             value_->SetType(NWebRomValue::Type::STRING);
552             value_->SetString(value);
553         }
554     }
555 
SetNumber(double value)556     void SetNumber(double value)
557     {
558         if (data_) {
559             data_->SetType(NWebValue::Type::DOUBLE);
560             data_->SetDouble(value);
561         }
562         if (value_) {
563             value_->SetType(NWebRomValue::Type::DOUBLE);
564             value_->SetDouble(value);
565         }
566     }
567 
SetBoolean(bool value)568     void SetBoolean(bool value)
569     {
570         if (data_) {
571             data_->SetType(NWebValue::Type::BOOLEAN);
572             data_->SetBoolean(value);
573         }
574         if (value_) {
575             value_->SetType(NWebRomValue::Type::BOOLEAN);
576             value_->SetBool(value);
577         }
578     }
579 
SetArrayBuffer(std::vector<uint8_t> & value)580     void SetArrayBuffer(std::vector<uint8_t>& value)
581     {
582         if (data_) {
583             data_->SetType(NWebValue::Type::BINARY);
584             data_->SetBinary(value);
585         }
586         if (value_) {
587             value_->SetType(NWebRomValue::Type::BINARY);
588             value_->SetBinary(value);
589         }
590     }
591 
SetStringArray(std::vector<std::string> value)592     void SetStringArray(std::vector<std::string> value)
593     {
594         if (data_) {
595             data_->SetType(NWebValue::Type::STRINGARRAY);
596             data_->SetStringArray(value);
597         }
598         if (value_) {
599             value_->SetType(NWebRomValue::Type::STRINGARRAY);
600             value_->SetStringArray(value);
601         }
602     }
603 
SetDoubleArray(std::vector<double> value)604     void SetDoubleArray(std::vector<double> value)
605     {
606         if (data_) {
607             data_->SetType(NWebValue::Type::DOUBLEARRAY);
608             data_->SetDoubleArray(value);
609         }
610         if (value_) {
611             value_->SetType(NWebRomValue::Type::DOUBLEARRAY);
612             value_->SetDoubleArray(value);
613         }
614     }
615 
SetInt64Array(std::vector<int64_t> value)616     void SetInt64Array(std::vector<int64_t> value)
617     {
618         if (data_) {
619             data_->SetType(NWebValue::Type::INT64ARRAY);
620             data_->SetInt64Array(value);
621         }
622         if (value_) {
623             value_->SetType(NWebRomValue::Type::INT64ARRAY);
624             value_->SetInt64Array(value);
625         }
626     }
627 
SetBooleanArray(std::vector<bool> value)628     void SetBooleanArray(std::vector<bool> value)
629     {
630         if (data_) {
631             data_->SetType(NWebValue::Type::BOOLEANARRAY);
632             data_->SetBooleanArray(value);
633         }
634         if (value_) {
635             value_->SetType(NWebRomValue::Type::BOOLEANARRAY);
636             value_->SetBoolArray(value);
637         }
638     }
639 
SetError(std::string name,std::string message)640     void SetError(std::string name, std::string message)
641     {
642         if (data_) {
643             data_->SetType(NWebValue::Type::ERROR);
644             data_->SetErrName(name);
645             data_->SetErrMsg(message);
646         }
647         if (value_) {
648             value_->SetType(NWebRomValue::Type::ERROR);
649             value_->SetErrName(name);
650             value_->SetErrMsg(message);
651         }
652     }
653 
GetData()654     std::shared_ptr<NWebMessage> GetData() const
655     {
656         return data_;
657     }
658 
GetValue()659     std::shared_ptr<NWebRomValue> GetValue() const
660     {
661         return value_;
662     }
663 
664 private:
665     int type_ = 0;
666     std::shared_ptr<NWebMessage> data_;
667     std::shared_ptr<NWebRomValue> value_;
668 };
669 
670 } // namespace NWeb
671 } // namespace OHOS
672 
673 #endif // NWEB_WEBVIEW_CONTROLLER_H
674