UniWebView.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. //
  2. // UniWebView.cs
  3. // Created by Wang Wei (@onevcat) on 2017-04-11.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // “as is” basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using UnityEngine;
  18. using System.Collections.Generic;
  19. using System;
  20. using System.Threading.Tasks;
  21. using UniWebViewExternal;
  22. /// <summary>
  23. /// Main class of UniWebView. Any `GameObject` instance with this script can represent a webview object in the scene.
  24. /// Use this class to create, load, show and interact with a general-purpose web view.
  25. /// </summary>
  26. public partial class UniWebView: MonoBehaviour {
  27. #region Serialize Fields
  28. // SerializeField that shows in Unity
  29. [SerializeField]
  30. private string urlOnStart;
  31. [SerializeField]
  32. private bool showOnStart = false;
  33. [SerializeField]
  34. private bool fullScreen;
  35. [SerializeField]
  36. private bool useEmbeddedToolbar;
  37. [SerializeField]
  38. private UniWebViewToolbarPosition embeddedToolbarPosition;
  39. [SerializeField]
  40. private Rect frame;
  41. [SerializeField]
  42. private RectTransform referenceRectTransform;
  43. #endregion
  44. #region Private Fields
  45. private string id = Guid.NewGuid().ToString();
  46. private UniWebViewNativeListener listener;
  47. private ScreenOrientation currentOrientation;
  48. private Rect currentUnmappedFrame;
  49. // Action callback holders
  50. private readonly Dictionary<String, Action> actions
  51. = new Dictionary<String, Action>();
  52. private readonly Dictionary<String, Action<UniWebViewNativeResultPayload>> payloadActions
  53. = new Dictionary<String, Action<UniWebViewNativeResultPayload>>();
  54. private static readonly Dictionary<String, Action<UniWebViewNativeResultPayload>> globalPayloadActions
  55. = new Dictionary<String, Action<UniWebViewNativeResultPayload>>();
  56. private bool started;
  57. private bool backButtonEnabled = true;
  58. private UniWebViewCornerRadius cornerRadius = UniWebViewCornerRadius.Zero;
  59. private UniWebViewShadow shadow = UniWebViewShadow.None;
  60. private string ListenerNameOrId => listener != null ? listener.Name : id;
  61. #endregion
  62. #region Unity Events
  63. void Awake() {
  64. var listenerObject = new GameObject(id);
  65. listener = listenerObject.AddComponent<UniWebViewNativeListener>();
  66. listenerObject.transform.parent = transform;
  67. listener.webView = this;
  68. UniWebViewNativeListener.AddListener(listener);
  69. EmbeddedToolbar = new UniWebViewEmbeddedToolbar(listener);
  70. var rect = NextFrameRect();
  71. SyncFramePropertyIfNeeded(rect);
  72. UniWebViewInterface.Init(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
  73. currentOrientation = Screen.orientation;
  74. currentUnmappedFrame = UnmappedFrame();
  75. // Register channel message handler
  76. RegisterChannelMessageHandler();
  77. }
  78. private Rect FullScreenFrame() {
  79. return NativeFrameRect(new Rect(0, 0, Screen.width, Screen.height));
  80. }
  81. void Start() {
  82. if (showOnStart) {
  83. Show();
  84. }
  85. if (useEmbeddedToolbar) {
  86. var config = UniWebViewEmbeddedToolbarConfig.Default;
  87. config.Position = embeddedToolbarPosition;
  88. config.Visible = true;
  89. EmbeddedToolbar.ApplyConfig(config);
  90. }
  91. if (!string.IsNullOrEmpty(urlOnStart)) {
  92. Load(urlOnStart);
  93. }
  94. started = true;
  95. if (referenceRectTransform != null) {
  96. UpdateFrame();
  97. }
  98. }
  99. void Update() {
  100. var newOrientation = Screen.orientation;
  101. var needUpdateFrame = false;
  102. if (currentOrientation != newOrientation) {
  103. currentOrientation = newOrientation;
  104. if (OnOrientationChanged != null) {
  105. OnOrientationChanged(this, newOrientation);
  106. }
  107. if (referenceRectTransform != null) {
  108. needUpdateFrame = true;
  109. }
  110. if (fullScreen) {
  111. needUpdateFrame = true;
  112. }
  113. }
  114. // The case that the screen size changes but the orientation does not change.
  115. // (Fold screen expanding, for example)
  116. var nextUnmappedFrame = UnmappedFrame();
  117. if (!currentUnmappedFrame.Equals(nextUnmappedFrame)) {
  118. currentUnmappedFrame = nextUnmappedFrame;
  119. needUpdateFrame = true;
  120. }
  121. if (needUpdateFrame) {
  122. UpdateFrame();
  123. }
  124. // Only the new input system is enabled. Related flags: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Installation.html#enabling-the-new-input-backends
  125. //
  126. // The new input system is not handling touchscreen events nicely as the old one.
  127. // The gesture detection hangs out regularly. Wait for an improvement of Unity.
  128. // So we choose to use the old one whenever it is available.
  129. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  130. var backDetected = backButtonEnabled && UnityEngine.InputSystem.Keyboard.current.escapeKey.wasPressedThisFrame;
  131. #else
  132. var backDetected = backButtonEnabled && Input.GetKeyUp(KeyCode.Escape);
  133. #endif
  134. if (backDetected) {
  135. UniWebViewLogger.Instance.Info(() => "Received Back button, handling GoBack or close web view.");
  136. if (CanGoBack) {
  137. GoBack();
  138. } else {
  139. InternalOnShouldClose();
  140. }
  141. }
  142. }
  143. void OnEnable() {
  144. if (started && listener != null) {
  145. _Show(useAsync: true);
  146. }
  147. }
  148. void OnDisable() {
  149. if (started && listener != null) {
  150. _Hide(useAsync: true);
  151. }
  152. }
  153. void OnDestroy() {
  154. var listenerName = ListenerNameOrId;
  155. CleanupSnapshotResources();
  156. InternalCloseAllPopupWindows(listenerName);
  157. UniWebViewNativeListener.RemoveListener(listenerName);
  158. UniWebViewChannelMethodManager.Instance.UnregisterChannel(listenerName);
  159. UniWebViewInterface.Destroy(listenerName);
  160. if (listener != null) {
  161. Destroy(listener.gameObject);
  162. }
  163. }
  164. #if UNITY_ANDROID && !UNITY_EDITOR
  165. // From Unity 2022.3.10, the player view is brought to front when switching back from a pause
  166. // state. Requiring to bring the web view to front to make the web view visible.
  167. // Issue caused by:
  168. // https://issuetracker.unity3d.com/issues/android-a-black-screen-appears-for-a-few-seconds-when-returning-to-the-game-from-the-lock-screen-after-idle-time
  169. //
  170. // Ref: UWV-1061
  171. void OnApplicationPause(bool pauseStatus) {
  172. if (RestoreViewHierarchyOnResume && !pauseStatus && listener != null) {
  173. UniWebViewInterface.BringContentToFront(listener.Name);
  174. }
  175. }
  176. #endif
  177. #endregion
  178. #region Capabilities
  179. /// <summary>
  180. /// Whether the web view is supported in current runtime or not.
  181. ///
  182. /// On some certain Android customized builds, the manufacturer prefers not containing the web view package in the
  183. /// system or blocks the web view package from being installed. If this happens, using of any web view related APIs will
  184. /// throw a `MissingWebViewPackageException` exception.
  185. ///
  186. /// Use this method to check whether the web view is available on the current running system. If this parameter returns `false`,
  187. /// you should not use the web view.
  188. ///
  189. /// This property always returns `true` on other supported platforms, such as iOS or macOS editor. It only performs
  190. /// runtime checking on Android. On other not supported platforms such as Windows or Linux, it always returns `false`.
  191. /// </summary>
  192. /// <value>Returns `true` if web view is supported on the current platform. Otherwise, `false`.</value>
  193. public static bool IsWebViewSupported {
  194. get {
  195. #if UNITY_EDITOR_OSX
  196. return true;
  197. #elif UNITY_EDITOR
  198. return false;
  199. #elif UNITY_IOS
  200. return true;
  201. #elif UNITY_STANDALONE_OSX
  202. return true;
  203. #elif UNITY_ANDROID
  204. return UniWebViewInterface.IsWebViewSupported();
  205. #else
  206. return false;
  207. #endif
  208. }
  209. }
  210. /// <summary>
  211. /// Gets the height of the status bar in pixels.
  212. ///
  213. /// When Unity is configured to render outside the safe area (i.e., full screen mode), this method returns 0.
  214. /// When the status bar is visible, it returns the actual pixel height of the status bar.
  215. ///
  216. /// On Android, it detects fullscreen and immersive modes to determine if the status bar is hidden.
  217. ///
  218. /// This method always returns 0 on iOS, macOS and other platforms for compatibility reasons.
  219. /// </summary>
  220. /// <returns>The status bar height in pixels on Android, or 0 on other platforms.</returns>
  221. private static int GetStatusBarHeight() {
  222. #if UNITY_ANDROID && !UNITY_EDITOR
  223. return UniWebViewInterface.GetStatusBarHeight();
  224. #else
  225. return 0;
  226. #endif
  227. }
  228. /// <summary>
  229. /// Sets whether the link clicking in the web view should open the page in an external browser.
  230. /// </summary>
  231. /// <param name="flag">The flag indicates whether a link should be opened externally.</param>
  232. public void SetOpenLinksInExternalBrowser(bool flag) {
  233. UniWebViewInterface.SetOpenLinksInExternalBrowser(listener.Name, flag);
  234. }
  235. /// <summary>
  236. /// Sets whether JavaScript should be enabled in current web view. Default is enabled.
  237. /// </summary>
  238. /// <param name="enabled">Whether JavaScript should be enabled.</param>
  239. public static void SetJavaScriptEnabled(bool enabled) {
  240. UniWebViewInterface.SetJavaScriptEnabled(enabled);
  241. }
  242. /// <summary>
  243. /// Sets allow auto play for current web view. By default,
  244. /// users need to touch the play button to start playing a media resource.
  245. ///
  246. /// By setting this to `true`, you can start the playing automatically through
  247. /// corresponding media tag attributes.
  248. /// </summary>
  249. /// <param name="flag">A flag indicates whether autoplaying of media is allowed or not.</param>
  250. public static void SetAllowAutoPlay(bool flag) {
  251. UniWebViewInterface.SetAllowAutoPlay(flag);
  252. }
  253. /// <summary>
  254. /// Sets allow inline play for current web view. By default, on iOS, the video
  255. /// can only be played in a new full screen view.
  256. /// By setting this to `true`, you could play a video inline the page, instead of opening
  257. /// a new full screen window.
  258. ///
  259. /// This only works for iOS and macOS Editor.
  260. /// On Android, you could play videos inline by default and calling this method does nothing.
  261. /// </summary>
  262. /// <param name="flag">A flag indicates whether inline playing of media is allowed or not.</param>
  263. public static void SetAllowInlinePlay(bool flag) {
  264. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  265. UniWebViewInterface.SetAllowInlinePlay(flag);
  266. #endif
  267. }
  268. /// <summary>
  269. /// Sets whether JavaScript can open windows without user interaction.
  270. ///
  271. /// By setting this to `true`, an automatically JavaScript navigation will be allowed in the web view.
  272. /// </summary>
  273. /// <param name="flag">Whether JavaScript could open window automatically.</param>
  274. public static void SetAllowJavaScriptOpenWindow(bool flag) {
  275. UniWebViewInterface.SetAllowJavaScriptOpenWindow(flag);
  276. }
  277. /// <summary>
  278. /// Sets whether the web page console output should be forwarded to native console.
  279. ///
  280. /// By setting this to `true`, UniWebView will try to intercept the web page console output methods and forward
  281. /// them to the native console, for example, Xcode console on iOS, Android logcat on Android and Unity Console when
  282. /// using Unity Editor on macOS. It provides a way to debug the web page by using the native console without opening
  283. /// the web inspector. The forwarded logs in native side contains a "&lt;UniWebView-Web&gt;" tag.
  284. ///
  285. /// Default is `false`. You need to set it before you create a web view instance to apply this setting. Any existing
  286. /// web views are not affected.
  287. ///
  288. /// Logs from the methods below will be forwarded:
  289. ///
  290. /// - console.log
  291. /// - console.warn
  292. /// - console.error
  293. /// - console.debug
  294. ///
  295. /// </summary>
  296. /// <param name="flag">Whether the web page console output should be forwarded to native output.</param>
  297. public static void SetForwardWebConsoleToNativeOutput(bool flag) {
  298. UniWebViewInterface.SetForwardWebConsoleToNativeOutput(flag);
  299. }
  300. /// <summary>
  301. /// Sets the way of how the cache is used when loading a request.
  302. ///
  303. /// The default value is `UniWebViewCacheMode.Default`.
  304. /// </summary>
  305. /// <param name="cacheMode">The desired cache mode which the following request loading should be used.</param>
  306. public void SetCacheMode(UniWebViewCacheMode cacheMode) {
  307. UniWebViewInterface.SetCacheMode(listener.Name, (int)cacheMode);
  308. }
  309. /// <summary>
  310. /// Sets whether the device back button should be enabled to execute "go back" or "closing" operation.
  311. ///
  312. /// On Android, the device back button in navigation bar will navigate users to a back page. If there is
  313. /// no any back page available, the back button clicking will try to raise a `OnShouldClose` event and try
  314. /// to close the web view if `true` is return from the event. If the `OnShouldClose` is not listened,
  315. /// the web view will be closed and the UniWebView component will be destroyed to release using resource.
  316. ///
  317. /// Listen to `OnKeyCodeReceived` if you need to disable the back button, but still want to get the back
  318. /// button key pressing event.
  319. ///
  320. /// Default is enabled.
  321. /// </summary>
  322. /// <param name="enabled">Whether the back button should perform go back or closing operation to web view.</param>
  323. public void SetBackButtonEnabled(bool enabled) {
  324. this.backButtonEnabled = enabled;
  325. }
  326. /// <summary>
  327. /// /// Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport.
  328. /// </summary>
  329. /// <param name="flag">Whether to enable support for the viewport meta tag.</param>
  330. public void SetUseWideViewPort(bool flag) {
  331. #if UNITY_ANDROID && !UNITY_EDITOR
  332. UniWebViewInterface.SetUseWideViewPort(listener.Name, flag);
  333. #endif
  334. }
  335. /// <summary>
  336. /// Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width.
  337. ///
  338. /// This method is only for Android. Default is disabled.
  339. /// </summary>
  340. /// <param name="flag"></param>
  341. public void SetLoadWithOverviewMode(bool flag) {
  342. #if UNITY_ANDROID && !UNITY_EDITOR
  343. UniWebViewInterface.SetLoadWithOverviewMode(listener.Name, flag);
  344. #endif
  345. }
  346. /// <summary>
  347. /// Enables debugging of web contents. You could inspect of the content of a
  348. /// web view by using a browser development tool of Chrome for Android or Safari for macOS.
  349. ///
  350. /// This method is only for Android and macOS Editor. On iOS, you do not need additional step.
  351. /// You could open Safari's developer tools to debug a web view on iOS.
  352. /// </summary>
  353. /// <param name="enabled">Whether the content debugging should be enabled.</param>
  354. public static void SetWebContentsDebuggingEnabled(bool enabled) {
  355. UniWebViewInterface.SetWebContentsDebuggingEnabled(enabled);
  356. }
  357. /// <summary>
  358. /// Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content.
  359. ///
  360. /// When enabled, when user long presses an image or link in the web page, a context menu would be show up to ask
  361. /// user's action. On iOS, it is a action sheet to ask whether opening the target link or saving the image. On
  362. /// Android it is a pop up dialog to ask whether saving the image to local disk. On iOS, the preview page triggered
  363. /// by force touch on iOS is also considered as a callout menu.
  364. ///
  365. /// Default is `true`, means that the callout menu will be displayed. Call this method with `false` to disable
  366. /// it on the web view.
  367. /// </summary>
  368. /// <param name="enabled">
  369. /// Whether a callout menu should be displayed when user long pressing or force touching a certain web page element.
  370. /// </param>
  371. public void SetCalloutEnabled(bool enabled) {
  372. UniWebViewInterface.SetCalloutEnabled(listener.Name, enabled);
  373. }
  374. /// <summary>
  375. /// Sets whether the web view should support a pop up web view triggered by user in a new tab.
  376. ///
  377. /// In a general web browser (such as Google Chrome or Safari), a URL with `target="_blank"` attribute is intended
  378. /// to be opened in a new tab. However, in the context of web view, there is no way to handle new tabs without
  379. /// proper configurations. Due to that, by default UniWebView will ignore the `target="_blank"` and try to open
  380. /// the page in the same web view if that kind of link is pressed.
  381. ///
  382. /// It works for most cases, but if this is a problem to your app logic, you can change this behavior by calling
  383. /// this method with `enabled` set to `true`. It enables the "opening in new tab" behavior in a limited way, by
  384. /// adding the new tab web view above to the current web view, with the same size and position. When the opened new
  385. /// tab is closed, it will be removed from the view hierarchy automatically.
  386. ///
  387. /// By default, only user triggered action is allowed to open a new window for security reason. That means, if you
  388. /// are using some JavaScript like `window.open`, unless you set `allowJavaScriptOpening` to `true`, it won't work.
  389. /// This default behavior prevents any other third party JavaScript code from opening a window arbitrarily.
  390. ///
  391. /// </summary>
  392. /// <param name="enabled">
  393. /// Whether to support multiple windows. If `true`, the `target="_blank"` link will be opened in a new web view.
  394. /// Default is `false`.
  395. /// </param>
  396. /// <param name="allowJavaScriptOpening">
  397. /// Whether to support open the new window with JavaScript by `window.open`. Setting this to `true` means any JavaScript
  398. /// code, even from third party (in an iframe or a library on the page), can open a new window. Use it as your risk.
  399. /// </param>
  400. public void SetSupportMultipleWindows(bool enabled, bool allowJavaScriptOpening) {
  401. UniWebViewInterface.SetSupportMultipleWindows(listener.Name, enabled, allowJavaScriptOpening);
  402. }
  403. /// <summary>
  404. /// Sets whether the drag interaction should be enabled on iOS.
  405. ///
  406. /// From iOS 11, the web view on iOS supports the drag interaction when user long presses an image, link or text.
  407. /// Setting this to `false` would disable the drag feather on the web view.
  408. ///
  409. /// On Android, there is no direct native way to disable drag only. This method instead disables the long touch
  410. /// event, which is used as a trigger for drag interaction. So, setting this to `false` would disable the long
  411. /// touch gesture as a side effect.
  412. ///
  413. /// It does nothing on macOS editor. Default is `true`, which means drag interaction is enabled if the device and
  414. /// system version supports it.
  415. /// </summary>
  416. /// <param name="enabled">
  417. /// Whether the drag interaction should be enabled.
  418. /// </param>
  419. public void SetDragInteractionEnabled(bool enabled) {
  420. UniWebViewInterface.SetDragInteractionEnabled(listener.Name, enabled);
  421. }
  422. #endregion
  423. #region Operations
  424. /// <summary>
  425. /// Sets whether this web view instance should try to restore its view hierarchy when resumed.
  426. ///
  427. /// In some versions of Unity when running on Android, the player view is brought to front when switching back
  428. /// from a pause state, which causes the web view is invisible when the app is resumed. It requires an additional
  429. /// step to bring the web view to front to make the web view visible. Set this to true to apply this workaround.
  430. ///
  431. /// Issue caused by:
  432. /// https://issuetracker.unity3d.com/issues/android-a-black-screen-appears-for-a-few-seconds-when-returning-to-the-game-from-the-lock-screen-after-idle-time
  433. ///
  434. /// This issue is known in these released versions:
  435. /// - Unity 2021.3.31, 2021.3.32, 2021.3.31, 2021.3.34
  436. /// - Unity 2022.3.10, 2022.3.11, 2022.3.12, 2022.3.13, 2022.3.14, 2022.3.15
  437. ///
  438. /// If you are using UniWebView in these versions, you may want to set this value to `true`.
  439. /// </summary>
  440. public bool RestoreViewHierarchyOnResume { get; set; }
  441. /// <summary>
  442. /// Adds a JavaScript to current page.
  443. /// </summary>
  444. /// <param name="jsString">The JavaScript code to add. It should be a valid JavaScript statement string.</param>
  445. /// <param name="completionHandler">Called when adding JavaScript operation finishes. Default is `null`.</param>
  446. public void AddJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  447. var identifier = Guid.NewGuid().ToString();
  448. UniWebViewInterface.AddJavaScript(listener.Name, jsString, identifier);
  449. if (completionHandler != null) {
  450. payloadActions.Add(identifier, completionHandler);
  451. }
  452. }
  453. /// <summary>
  454. /// Evaluates a JavaScript string on current page.
  455. /// </summary>
  456. /// <param name="jsString">The JavaScript string to evaluate.</param>
  457. /// <param name="completionHandler">Called when evaluating JavaScript operation finishes. Default is `null`.</param>
  458. public void EvaluateJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  459. var identifier = Guid.NewGuid().ToString();
  460. UniWebViewInterface.EvaluateJavaScript(listener.Name, jsString, identifier);
  461. if (completionHandler != null) {
  462. payloadActions.Add(identifier, completionHandler);
  463. }
  464. }
  465. /// <summary>
  466. /// Cleans web view cache. This removes cached local data of web view.
  467. ///
  468. /// If you need to clear all cookies, use `ClearCookies` instead.
  469. /// </summary>
  470. /// <param name="includeStorage">
  471. /// Whether to include storage data (such as local database in the web page) when cleaning cache. Default `false`.
  472. /// </param>
  473. /// <param name="completionHandler">
  474. /// An action that is called after the operation finishes.
  475. /// </param>
  476. public void CleanCache(bool includeStorage = false, Action completionHandler = null) {
  477. var identifier = Guid.NewGuid().ToString();
  478. if (completionHandler != null) {
  479. actions.Add(identifier, completionHandler);
  480. }
  481. UniWebViewInterface.CleanCache(listener.Name, includeStorage, identifier);
  482. }
  483. /// <summary>
  484. /// Gets the HTML content from current page by accessing its outerHTML with JavaScript.
  485. /// </summary>
  486. /// <param name="handler">Called after the JavaScript executed. The parameter string is the content read
  487. /// from page.</param>
  488. public void GetHTMLContent(Action<string> handler) {
  489. EvaluateJavaScript("document.documentElement.outerHTML", payload => {
  490. if (handler != null) {
  491. handler(payload.data);
  492. }
  493. });
  494. }
  495. /// <summary>
  496. /// Prints current page.
  497. ///
  498. /// By calling this method, a native print preview panel will be brought up on iOS and Android.
  499. /// This method does nothing on macOS editor.
  500. /// On iOS and Android, the web view does not support JavaScript (window.print()),
  501. /// you can only initialize a print job from Unity by this method.
  502. /// </summary>
  503. public void Print() {
  504. UniWebViewInterface.Print(listener.Name);
  505. }
  506. #endregion
  507. #region Channel
  508. /// <summary>
  509. /// Registers a method handler for deciding whether UniWebView should handle the request received by the web view.
  510. ///
  511. /// The handler is called before the web view actually starts to load the new request. You can check the request
  512. /// properties, such as the URL, to decide whether UniWebView should continue to handle the request or not. If you
  513. /// return `true` from the handler function, UniWebView will continue to load the request. Otherwise, UniWebView
  514. /// will stop the loading.
  515. /// </summary>
  516. /// <param name="handler">
  517. /// A handler you can implement your own logic against the input request value. You need to return a boolean value
  518. /// to indicate whether UniWebView should continue to load the request or not as soon as possible.
  519. /// </param>
  520. public void RegisterShouldHandleRequest(Func<UniWebViewChannelMethodHandleRequest, bool> handler) {
  521. object Func(object obj) => handler((UniWebViewChannelMethodHandleRequest)obj);
  522. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  523. listener.Name,
  524. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest,
  525. Func
  526. );
  527. }
  528. /// <summary>
  529. /// Unregisters the method handler for handling request received by the web view.
  530. ///
  531. /// This clears the handler registered by `RegisterHandlingRequest` method.
  532. /// </summary>
  533. public void UnregisterShouldHandleRequest() {
  534. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  535. listener.Name,
  536. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest
  537. );
  538. }
  539. /// <summary>
  540. /// Registers a method handler for deciding whether UniWebView should allow a media request from the web page or
  541. /// not.
  542. ///
  543. /// The handler is called when the web view receives a request to capture media, such as camera or microphone. It
  544. /// usually happens when the web view is trying to access the camera or microphone by using the "getUserMedia" APIs
  545. /// in WebRTC. You can check the request properties in the input `UniWebViewChannelMethodMediaCapturePermission`
  546. /// instance, which contains information like the media type, the request origin (protocol and host), then decide
  547. /// whether this media request should be allowed or not.
  548. ///
  549. /// According to the `UniWebViewMediaCapturePermissionDecision` value you return from the handler function,
  550. /// UniWebView behaves differently:
  551. ///
  552. /// - `Grant`: UniWebView allows the access without asking the user.
  553. /// - `Deny`: UniWebView forbids the access and the web page will receive an error.
  554. /// - `Prompt`: UniWebView asks the user for permission. The web page will receive a prompt to ask the user if they
  555. /// allow the access to the requested media resources (camera or/and microphone).
  556. ///
  557. /// If this method is never called or the handler is unregistered, UniWebView will prompt the user for the
  558. /// permission.
  559. ///
  560. /// On iOS, this method is available from iOS 15.0 or later. On earlier version of iOS, the handler will be ignored
  561. /// and the web view will always prompt the user for the permission.
  562. ///
  563. /// </summary>
  564. /// <param name="handler">
  565. /// A handler you can implement your own logic to decide whether UniWebView should allow, deny or prompt the media
  566. /// resource access request.
  567. ///
  568. /// You need to return a `UniWebViewMediaCapturePermissionDecision` value to indicate the decision as soon as
  569. /// possible.
  570. /// </param>
  571. public void RegisterOnRequestMediaCapturePermission(
  572. Func<
  573. UniWebViewChannelMethodMediaCapturePermission,
  574. UniWebViewMediaCapturePermissionDecision
  575. > handler
  576. )
  577. {
  578. object Func(object obj) => handler((UniWebViewChannelMethodMediaCapturePermission)obj);
  579. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  580. listener.Name,
  581. UniWebViewChannelMethod.RequestMediaCapturePermission,
  582. Func
  583. );
  584. }
  585. /// <summary>
  586. /// Unregisters the method handler for handling media capture permission request.
  587. ///
  588. /// This clears the handler registered by `RegisterOnRequestMediaCapturePermission` method.
  589. /// </summary>
  590. public void UnregisterOnRequestMediaCapturePermission() {
  591. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  592. listener.Name,
  593. UniWebViewChannelMethod.RequestMediaCapturePermission
  594. );
  595. }
  596. /// <summary>
  597. /// Registers a method handler for embedded toolbar item actions.
  598. ///
  599. /// This handler is invoked synchronously before native performs the default action for built-in embedded toolbar
  600. /// items (back/forward/done/reload/title interactions). Return <c>true</c> to mark the action as handled and skip
  601. /// native default behavior. Return <c>false</c> to let native continue with the default behavior.
  602. ///
  603. /// For title interactions, whether tap/long-press can trigger depends on the toolbar config item's
  604. /// <c>titleInteraction</c> settings.
  605. /// </summary>
  606. /// <param name="handler">The synchronous action handler. Return <c>true</c> to intercept.</param>
  607. public void RegisterOnEmbeddedToolbarItemAction(
  608. Func<UniWebViewChannelMethodEmbeddedToolbarItemAction, bool> handler
  609. )
  610. {
  611. object Func(object obj) => handler((UniWebViewChannelMethodEmbeddedToolbarItemAction)obj);
  612. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  613. listener.Name,
  614. UniWebViewChannelMethod.EmbeddedToolbarItemAction,
  615. Func
  616. );
  617. }
  618. /// <summary>
  619. /// Unregisters the method handler for embedded toolbar item actions.
  620. /// </summary>
  621. public void UnregisterOnEmbeddedToolbarItemAction() {
  622. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  623. listener.Name,
  624. UniWebViewChannelMethod.EmbeddedToolbarItemAction
  625. );
  626. }
  627. // Register channel message handler
  628. private void RegisterChannelMessageHandler() {
  629. object Func(object obj) => HandleChannelMessage((UniWebViewChannelMessage)obj);
  630. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  631. listener.Name,
  632. UniWebViewChannelMethod.ChannelMessage,
  633. Func
  634. );
  635. }
  636. // Handle incoming channel messages
  637. private UniWebViewChannelMessageResponse HandleChannelMessage(UniWebViewChannelMessage rawMessage) {
  638. // Create message with respond delegate for async responses
  639. var message = new UniWebViewChannelMessage(
  640. rawMessage.id,
  641. rawMessage.timestamp,
  642. rawMessage.action,
  643. rawMessage.data,
  644. rawMessage.messageType,
  645. SendChannelMessageResponseInternal
  646. );
  647. UniWebViewChannelMessageResponse response = null;
  648. // Log message type for debugging
  649. UniWebViewLogger.Instance.Debug(() => $"Processing {message.MessageType} message for action '{message.action}'");
  650. if (OnChannelMessageReceived != null) {
  651. try {
  652. response = OnChannelMessageReceived(this, message);
  653. // Validate response consistency with message type
  654. ValidateMessageResponse(message, response);
  655. } catch (System.Exception e) {
  656. UniWebViewLogger.Instance.Critical(() => $"Error in channel message handler: {e.Message}");
  657. response = UniWebViewChannelMessageResponse.Error("Handler execution failed: " + e.Message);
  658. }
  659. }
  660. return response;
  661. }
  662. // Validates that the response is appropriate for the message type
  663. private void ValidateMessageResponse(UniWebViewChannelMessage message, UniWebViewChannelMessageResponse response) {
  664. switch (message.MessageType) {
  665. case UniWebViewChannelMessageType.Send:
  666. if (response != null) {
  667. UniWebViewLogger.Instance.Warning(() => $"Send message '{message.action}' returned a response, but Send messages should return null (fire-and-forget)");
  668. }
  669. break;
  670. case UniWebViewChannelMessageType.Call:
  671. if (response == null) {
  672. UniWebViewLogger.Instance.Warning(() => $"Call message '{message.action}' returned null, but Call messages should return a response for immediate return to JavaScript");
  673. }
  674. break;
  675. case UniWebViewChannelMessageType.Request:
  676. // Request messages should always return null and use message.Respond() for async responses
  677. if (response != null) {
  678. UniWebViewLogger.Instance.Warning(() => $"Request message '{message.action}' returned a response, but Request messages should return null and use message.Respond() for async responses");
  679. } else {
  680. UniWebViewLogger.Instance.Debug(() => $"Request message '{message.action}' will respond later via message.Respond()");
  681. }
  682. break;
  683. }
  684. }
  685. // Internal method for async responses (called by UniWebViewChannelMessage.Respond)
  686. internal void SendChannelMessageResponseInternal(string messageId, UniWebViewChannelMessageResponse response) {
  687. try {
  688. // Escape the messageId to prevent XSS
  689. var escapedMessageId = messageId.Replace("'", "\\'").Replace("\"", "\\\"");
  690. string responseString;
  691. var errorFlag = response.hasError ? "true" : "false";
  692. if (response.hasError) {
  693. // For error responses, use JSON serialization (supports structured error objects)
  694. responseString = UniWebViewJsonUtility.ToJson(response.errorData);
  695. } else {
  696. // For success responses, use JSON serialization
  697. responseString = UniWebViewJsonUtility.ToJson(response.data);
  698. }
  699. var js = $"window.uniwebview._handleResponse('{escapedMessageId}', {responseString}, {errorFlag});";
  700. EvaluateJavaScript(js, (payload) => {
  701. if (payload.resultCode.Equals("0")) {
  702. UniWebViewLogger.Instance.Debug(() => "Channel message response sent successfully");
  703. } else {
  704. UniWebViewLogger.Instance.Critical(() => $"Failed to send channel message response: {payload.data}");
  705. }
  706. });
  707. } catch (System.Exception e) {
  708. UniWebViewLogger.Instance.Critical(() => $"Failed to send async response: {e.Message}");
  709. }
  710. }
  711. #endregion
  712. }