UniWebView.UI.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. //
  2. // UniWebView.UI.cs
  3. // Created by Wang Wei (@onevcat) on 2025-04-19.
  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 System;
  18. using UnityEngine;
  19. public partial class UniWebView {
  20. /// <summary>
  21. /// Represents the embedded toolbar in the current web view.
  22. /// </summary>
  23. public UniWebViewEmbeddedToolbar EmbeddedToolbar { get; private set; }
  24. /// <summary>
  25. /// Gets or sets the frame of current web view. The value is based on current `Screen.width` and `Screen.height`.
  26. /// The first two values of `Rect` is `x` and `y` position and the followed two `width` and `height`.
  27. /// </summary>
  28. public Rect Frame {
  29. get => frame;
  30. set {
  31. fullScreen = false;
  32. frame = value;
  33. UpdateFrame();
  34. }
  35. }
  36. /// <summary>
  37. /// A reference rect transform which the web view should change its position and size to.
  38. /// Set it to a Unity UI element (which contains a `RectTransform`) under a canvas to determine
  39. /// the web view frame by a certain UI element.
  40. ///
  41. /// By using this, you could get benefit from [Multiple Resolutions UI](https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html).
  42. ///
  43. /// </summary>
  44. public RectTransform ReferenceRectTransform {
  45. get => referenceRectTransform;
  46. set {
  47. fullScreen = false;
  48. referenceRectTransform = value;
  49. UpdateFrame();
  50. }
  51. }
  52. private bool loggedLegacyToolbarSuppressedByEmbeddedToolbar;
  53. #pragma warning disable 618
  54. private bool ShouldDriveLegacyToolbar() {
  55. if (!useToolbar) {
  56. return false;
  57. }
  58. if (!useEmbeddedToolbar) {
  59. return true;
  60. }
  61. if (!loggedLegacyToolbarSuppressedByEmbeddedToolbar) {
  62. loggedLegacyToolbarSuppressedByEmbeddedToolbar = true;
  63. UniWebViewLogger.Instance.Warning(() =>
  64. "Detected legacy toolbar flag (useToolbar=true) together with embedded toolbar (useEmbeddedToolbar=true). " +
  65. "Suppressing legacy toolbar to avoid duplicate toolbars. Please update old prefab/scene serialization.");
  66. }
  67. return false;
  68. }
  69. #pragma warning restore 618
  70. /// <summary>
  71. /// Updates and sets current frame of web view to match the setting.
  72. ///
  73. /// This is useful if the `referenceRectTransform` is changed and you need to sync the frame change
  74. /// to the web view. This method follows the frame determining rules.
  75. /// </summary>
  76. public void UpdateFrame() {
  77. Rect rect = NextFrameRect();
  78. SyncFramePropertyIfNeeded(rect);
  79. UniWebViewInterface.SetFrame(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
  80. }
  81. void SyncFramePropertyIfNeeded(Rect rect) {
  82. if (fullScreen || referenceRectTransform != null) {
  83. frame = rect;
  84. }
  85. }
  86. Rect UnmappedFrame() {
  87. if (fullScreen) {
  88. return new Rect(0, 0, Screen.width, Screen.height);
  89. }
  90. return referenceRectTransform != null ? referenceRectTransform.rect : frame;
  91. }
  92. Rect NextFrameRect() {
  93. if (fullScreen) {
  94. return FullScreenFrame();
  95. }
  96. if (referenceRectTransform == null) {
  97. UniWebViewLogger.Instance.Info("Using Frame setting to determine web view frame.");
  98. return NativeFrameRect(frame);
  99. }
  100. UniWebViewLogger.Instance.Info("Using reference RectTransform to determine web view frame.");
  101. var worldCorners = new Vector3[4];
  102. referenceRectTransform.GetWorldCorners(worldCorners);
  103. // var bottomLeft = worldCorners[0];
  104. var topLeft = worldCorners[1];
  105. // var topRight = worldCorners[2];
  106. var bottomRight = worldCorners[3];
  107. var canvas = referenceRectTransform.GetComponentInParent<Canvas>();
  108. if (canvas == null) {
  109. return frame;
  110. }
  111. switch (canvas.renderMode) {
  112. case RenderMode.ScreenSpaceOverlay:
  113. break;
  114. case RenderMode.ScreenSpaceCamera:
  115. case RenderMode.WorldSpace:
  116. var camera = canvas.worldCamera;
  117. if (camera == null) {
  118. UniWebViewLogger.Instance.Critical(@"You need a render camera
  119. or event camera to use RectTransform to determine correct
  120. frame for UniWebView.");
  121. UniWebViewLogger.Instance.Info("No camera found. Fall back to ScreenSpaceOverlay mode.");
  122. } else {
  123. // bottomLeft = camera.WorldToScreenPoint(bottomLeft);
  124. topLeft = camera.WorldToScreenPoint(topLeft);
  125. // topRight = camera.WorldToScreenPoint(topRight);
  126. bottomRight = camera.WorldToScreenPoint(bottomRight);
  127. }
  128. break;
  129. default:
  130. throw new ArgumentOutOfRangeException();
  131. }
  132. var unityFrame = new Rect(
  133. topLeft.x,
  134. Screen.height - topLeft.y,
  135. bottomRight.x - topLeft.x,
  136. topLeft.y - bottomRight.y
  137. );
  138. return NativeFrameRect(unityFrame);
  139. }
  140. private Rect NativeFrameRect(Rect unityFrame) {
  141. #if UNITY_IOS && !UNITY_EDITOR
  142. return CalculateCocoaNativeFrameRect(
  143. unityFrame,
  144. Screen.width,
  145. Screen.height,
  146. UniWebViewInterface.NativeScreenWidth(),
  147. UniWebViewInterface.NativeScreenHeight(),
  148. GetStatusBarHeight()
  149. );
  150. #elif UNITY_ANDROID && !UNITY_EDITOR
  151. try {
  152. var padding = UniWebViewInterface.GetContentViewPadding();
  153. if (padding[0] != 0 || padding[1] != 0 || padding[2] != 0 || padding[3] != 0) {
  154. return CalculateNativeFrameRectWithContentPadding(
  155. unityFrame,
  156. Screen.width,
  157. Screen.height,
  158. UniWebViewInterface.NativeScreenWidth(),
  159. UniWebViewInterface.NativeScreenHeight(),
  160. padding[0], padding[1], padding[2], padding[3]
  161. );
  162. }
  163. return CalculateNativeFrameRect(
  164. unityFrame,
  165. Screen.width,
  166. Screen.height,
  167. UniWebViewInterface.NativeScreenWidth(),
  168. UniWebViewInterface.NativeScreenHeight(),
  169. GetStatusBarHeight()
  170. );
  171. } catch (Exception e) {
  172. UniWebViewLogger.Instance.Warning(() =>
  173. $"Failed to calculate Android native frame: {e.Message}. Falling back to Unity frame.");
  174. }
  175. return unityFrame;
  176. #else
  177. return unityFrame;
  178. #endif
  179. }
  180. // Cocoa receives physical-pixel coordinates and converts them to points using its backing
  181. // scale. Unity's render resolution may be lower than that physical viewport, so a
  182. // RectTransform frame needs this mapping before crossing the native boundary.
  183. private static Rect CalculateCocoaNativeFrameRect(
  184. Rect unityFrame,
  185. float unityScreenWidth,
  186. float unityScreenHeight,
  187. float nativeScreenWidth,
  188. float nativeScreenHeight,
  189. float statusBarHeight
  190. ) {
  191. return CalculateNativeFrameRect(
  192. unityFrame,
  193. unityScreenWidth,
  194. unityScreenHeight,
  195. nativeScreenWidth,
  196. nativeScreenHeight,
  197. statusBarHeight
  198. );
  199. }
  200. private static Rect CalculateNativeFrameRect(
  201. Rect unityFrame,
  202. float unityScreenWidth,
  203. float unityScreenHeight,
  204. float nativeScreenWidth,
  205. float nativeScreenHeight,
  206. float statusBarHeight
  207. ) {
  208. if (unityScreenWidth <= 0 || unityScreenHeight <= 0 || nativeScreenWidth <= 0 || nativeScreenHeight <= 0) {
  209. return unityFrame;
  210. }
  211. var contentHeight = Mathf.Max(0, nativeScreenHeight - statusBarHeight);
  212. var widthFactor = nativeScreenWidth / unityScreenWidth;
  213. var heightFactor = contentHeight / unityScreenHeight;
  214. return new Rect(
  215. unityFrame.x * widthFactor,
  216. statusBarHeight + unityFrame.y * heightFactor,
  217. unityFrame.width * widthFactor,
  218. unityFrame.height * heightFactor
  219. );
  220. }
  221. // Maps a Unity frame into native coordinates when the host app applies window insets as
  222. // padding on the native content view (the pattern recommended by Google for edge-to-edge
  223. // enforcement since Android 15). In that layout the Unity player view occupies the padded
  224. // area of the content view, while UniWebView's container is positioned in the content
  225. // view's full coordinate space, so the frame is offset by the padding origin and scaled
  226. // into the padded area.
  227. private static Rect CalculateNativeFrameRectWithContentPadding(
  228. Rect unityFrame,
  229. float unityScreenWidth,
  230. float unityScreenHeight,
  231. float nativeScreenWidth,
  232. float nativeScreenHeight,
  233. float paddingLeft,
  234. float paddingTop,
  235. float paddingRight,
  236. float paddingBottom
  237. ) {
  238. if (unityScreenWidth <= 0 || unityScreenHeight <= 0 || nativeScreenWidth <= 0 || nativeScreenHeight <= 0) {
  239. return unityFrame;
  240. }
  241. var paddedWidth = nativeScreenWidth - paddingLeft - paddingRight;
  242. var paddedHeight = nativeScreenHeight - paddingTop - paddingBottom;
  243. if (paddedWidth <= 0 || paddedHeight <= 0) {
  244. return unityFrame;
  245. }
  246. var widthFactor = paddedWidth / unityScreenWidth;
  247. var heightFactor = paddedHeight / unityScreenHeight;
  248. return new Rect(
  249. paddingLeft + unityFrame.x * widthFactor,
  250. paddingTop + unityFrame.y * heightFactor,
  251. unityFrame.width * widthFactor,
  252. unityFrame.height * heightFactor
  253. );
  254. }
  255. /// <summary>
  256. /// Applies a transformation to the web view, including rotation and scaling.
  257. ///
  258. /// This method allows you to rotate and scale the web view by specifying a <see cref="UniWebViewTransform"/>
  259. /// object. The transformation is applied relative to the web view's current position and size, with its center
  260. /// as the anchor.
  261. ///
  262. /// The transformation includes:
  263. /// - **Rotation**: The angle (in degrees) by which the web view should be rotated. Positive values rotate the web
  264. /// view clockwise, while negative values rotate it counterclockwise.
  265. /// - **Scaling**: The scale factors for the X and Y axes. A scale factor of 1.0 means no scaling, while values
  266. /// greater than 1.0 enlarge the web view and values less than 1.0 shrink it.
  267. ///
  268. /// This method works on iOS and Android. It does nothing in Unity Editor on macOS.
  269. ///
  270. /// </summary>
  271. /// <param name="transform">
  272. /// A <see cref="UniWebViewTransform"/> object containing the rotation angle and scale factors to apply to the web
  273. /// view.
  274. /// </param>
  275. public void SetTransform(UniWebViewTransform transform) {
  276. UniWebViewInterface.SetTransform(listener.Name, transform.Rotation, transform.ScaleX, transform.ScaleY);
  277. }
  278. /// <summary>
  279. /// Gets the current round corner radius applied to this web view.
  280. /// </summary>
  281. public UniWebViewCornerRadius CornerRadius => cornerRadius;
  282. /// <summary>
  283. /// Gets the current shadow configuration applied to this web view.
  284. /// </summary>
  285. public UniWebViewShadow Shadow => shadow;
  286. /// <summary>
  287. /// Sets the same round corner radius value for all corners.
  288. /// </summary>
  289. /// <param name="radius">The radius applied to every corner.</param>
  290. public void SetRoundCornerRadius(float radius) {
  291. SetRoundCornerRadius(UniWebViewCornerRadius.Uniform(radius));
  292. }
  293. /// <summary>
  294. /// Sets round corner radius values for each individual corner.
  295. /// </summary>
  296. /// <param name="topLeft">Radius at the top-left corner.</param>
  297. /// <param name="topRight">Radius at the top-right corner.</param>
  298. /// <param name="bottomLeft">Radius at the bottom-left corner.</param>
  299. /// <param name="bottomRight">Radius at the bottom-right corner.</param>
  300. public void SetRoundCornerRadius(
  301. float topLeft,
  302. float topRight,
  303. float bottomLeft,
  304. float bottomRight
  305. ) {
  306. SetRoundCornerRadius(new UniWebViewCornerRadius(topLeft, topRight, bottomLeft, bottomRight));
  307. }
  308. /// <summary>
  309. /// Applies the provided round corner radius configuration to the native web view.
  310. /// </summary>
  311. /// <param name="radius">The corner radius definition.</param>
  312. public void SetRoundCornerRadius(UniWebViewCornerRadius radius) {
  313. cornerRadius = radius;
  314. UniWebViewInterface.SetRoundCornerRadius(
  315. listener.Name,
  316. radius.TopLeft,
  317. radius.TopRight,
  318. radius.BottomLeft,
  319. radius.BottomRight
  320. );
  321. }
  322. /// <summary>
  323. /// Applies the provided shadow configuration to the web view container.
  324. /// </summary>
  325. /// <param name="value">The shadow definition.</param>
  326. public void SetShadow(UniWebViewShadow value) {
  327. shadow = value;
  328. UniWebViewInterface.SetShadow(
  329. listener.Name,
  330. value.Color.r,
  331. value.Color.g,
  332. value.Color.b,
  333. value.Color.a,
  334. value.Opacity,
  335. value.Radius,
  336. value.OffsetX,
  337. value.OffsetY,
  338. value.Spread
  339. );
  340. }
  341. /// <summary>
  342. /// Convenience overload to set shadow properties.
  343. /// </summary>
  344. /// <param name="radius">Shadow blur radius.</param>
  345. /// <param name="opacity">Shadow opacity (0 - 1).</param>
  346. /// <param name="offset">Shadow offset.</param>
  347. /// <param name="color">Shadow color.</param>
  348. /// <param name="spread">Shadow spread distance.</param>
  349. public void SetShadow(float radius, float opacity, Vector2 offset, Color color, float spread = 0.0f) {
  350. SetShadow(new UniWebViewShadow(radius, opacity, offset.x, offset.y, color, spread));
  351. }
  352. /// <summary>
  353. /// Sets the web view visible on screen.
  354. ///
  355. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  356. /// be applied when showing. So the `duration` parameter will not be taken into account. Otherwise, when
  357. /// either or both `fade` and `edge` set, the showing operation will be animated.
  358. ///
  359. /// Regardless of there is an animation or not, the `completionHandler` will be called if not `null` when the web
  360. /// view showing finishes.
  361. /// </summary>
  362. /// <param name="fade">Whether show with a fade in animation. Default is `false`.</param>
  363. /// <param name="edge">The edge from which the web view showing. It simulates a modal effect when showing a web view. Default is `UniWebViewTransitionEdge.None`.</param>
  364. /// <param name="duration">Duration of the showing animation. Default is `0.4f`.</param>
  365. /// <param name="completionHandler">Completion handler which will be called when showing finishes. Default is `null`.</param>
  366. /// <returns>A bool value indicates whether the showing operation started.</returns>
  367. public bool Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  368. float duration = 0.4f, Action completionHandler = null)
  369. {
  370. return _Show(fade, edge, duration, false, completionHandler);
  371. }
  372. public bool _Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  373. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  374. {
  375. var identifier = Guid.NewGuid().ToString();
  376. var showStarted = UniWebViewInterface.Show(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  377. if (showStarted && completionHandler != null) {
  378. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  379. if (hasAnimation) {
  380. actions.Add(identifier, completionHandler);
  381. } else {
  382. completionHandler();
  383. }
  384. }
  385. #pragma warning disable 618
  386. if (showStarted && ShouldDriveLegacyToolbar()) {
  387. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  388. SetShowToolbar(true, false, top, fullScreen);
  389. }
  390. #pragma warning restore 618
  391. return showStarted;
  392. }
  393. /// <summary>
  394. /// Sets the web view invisible from screen.
  395. ///
  396. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  397. /// be applied when hiding. So the `duration` parameter will not be taken into account. Otherwise, when either or
  398. /// both `fade` and `edge` set, the hiding operation will be animated.
  399. ///
  400. /// Regardless there is an animation or not, the `completionHandler` will be called if not `null` when the web view
  401. /// hiding finishes.
  402. /// </summary>
  403. /// <param name="fade">Whether hide with a fade in animation. Default is `false`.</param>
  404. /// <param name="edge">The edge from which the web view hiding. It simulates a modal effect when hiding a web view. Default is `UniWebViewTransitionEdge.None`.</param>
  405. /// <param name="duration">Duration of hiding animation. Default is `0.4f`.</param>
  406. /// <param name="completionHandler">Completion handler which will be called when hiding finishes. Default is `null`.</param>
  407. /// <returns>A bool value indicates whether the hiding operation started.</returns>
  408. public bool Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  409. float duration = 0.4f, Action completionHandler = null)
  410. {
  411. return _Hide(fade, edge, duration, false, completionHandler);
  412. }
  413. public bool _Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  414. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  415. {
  416. var identifier = Guid.NewGuid().ToString();
  417. var hideStarted = UniWebViewInterface.Hide(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  418. if (hideStarted && completionHandler != null) {
  419. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  420. if (hasAnimation) {
  421. actions.Add(identifier, completionHandler);
  422. } else {
  423. completionHandler();
  424. }
  425. }
  426. #pragma warning disable 618
  427. if (hideStarted && ShouldDriveLegacyToolbar()) {
  428. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  429. SetShowToolbar(false, false, top, fullScreen);
  430. }
  431. #pragma warning restore 618
  432. return hideStarted;
  433. }
  434. /// <summary>
  435. /// Animates the web view from current position and size to another position and size.
  436. /// </summary>
  437. /// <param name="frame">The new `Frame` which the web view should be.</param>
  438. /// <param name="duration">Duration of the animation.</param>
  439. /// <param name="delay">Delay before the animation begins. Default is `0.0f`, which means the animation will start immediately.</param>
  440. /// <param name="completionHandler">Completion handler which will be called when animation finishes. Default is `null`.</param>
  441. /// <returns></returns>
  442. public bool AnimateTo(Rect frame, float duration, float delay = 0.0f, Action completionHandler = null) {
  443. var identifier = Guid.NewGuid().ToString();
  444. var nativeFrame = NativeFrameRect(frame);
  445. var animationStarted = UniWebViewInterface.AnimateTo(listener.Name,
  446. (int)nativeFrame.x, (int)nativeFrame.y, (int)nativeFrame.width, (int)nativeFrame.height, duration, delay, identifier);
  447. if (animationStarted) {
  448. this.frame = frame;
  449. if (completionHandler != null) {
  450. actions.Add(identifier, completionHandler);
  451. }
  452. }
  453. return animationStarted;
  454. }
  455. /// <summary>
  456. /// Sets the adjustment behavior which indicates how safe area insets
  457. /// are added to the adjusted content inset. It is a wrapper of `contentInsetAdjustmentBehavior` on iOS.
  458. ///
  459. /// It only works on iOS 11 and above. You need to call this method as soon as you create a web view,
  460. /// before you call any other methods related to web view layout (like `Show` or `SetShowToolbar`).
  461. /// </summary>
  462. /// <param name="behavior">The behavior for determining the adjusted content offsets.</param>
  463. public void SetContentInsetAdjustmentBehavior(
  464. UniWebViewContentInsetAdjustmentBehavior behavior
  465. )
  466. {
  467. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  468. UniWebViewInterface.SetContentInsetAdjustmentBehavior(listener.Name, behavior);
  469. #endif
  470. }
  471. /// <summary>
  472. /// Sets whether the web view area should avoid soft keyboard. If `true`, when the keyboard shows up, the web views
  473. /// content view will resize itself to avoid keyboard overlap the web content. Otherwise, the web view will not resize
  474. /// and just leave the content below under the soft keyboard.
  475. ///
  476. /// This method is only for Android. On iOS, the keyboard avoidance is built into the system directly and there is
  477. /// no way to change its behavior.
  478. ///
  479. /// Default is `true`.
  480. /// </summary>
  481. /// <param name="flag">Whether the keyboard should avoid web view content.</param>
  482. public static void SetEnableKeyboardAvoidance(bool flag) {
  483. #if UNITY_ANDROID && !UNITY_EDITOR
  484. UniWebViewInterface.SetEnableKeyboardAvoidance(flag);
  485. #endif
  486. }
  487. private Color backgroundColor = Color.white;
  488. /// <summary>
  489. /// Gets or sets the background color of web view. The default value is `Color.white`.
  490. /// </summary>
  491. public Color BackgroundColor {
  492. get => backgroundColor;
  493. set {
  494. backgroundColor = value;
  495. UniWebViewInterface.SetBackgroundColor(listener.Name, value.r, value.g, value.b, value.a);
  496. }
  497. }
  498. /// <summary>
  499. /// Gets or sets the alpha value of the whole web view.
  500. ///
  501. /// You can make the game scene behind web view visible to make the web view transparent.
  502. ///
  503. /// Default is `1.0f`, which means totally opaque. Set it to `0.0f` will make the web view totally transparent.
  504. /// </summary>
  505. public float Alpha {
  506. get => UniWebViewInterface.GetWebViewAlpha(listener.Name);
  507. set => UniWebViewInterface.SetWebViewAlpha(listener.Name, value);
  508. }
  509. /// <summary>
  510. /// Sets whether to show a loading indicator while the loading is in progress.
  511. /// </summary>
  512. /// <param name="flag">Whether an indicator should show.</param>
  513. public void SetShowSpinnerWhileLoading(bool flag) {
  514. UniWebViewInterface.SetShowSpinnerWhileLoading(listener.Name, flag);
  515. }
  516. /// <summary>
  517. /// Sets the text displayed in the loading indicator, if `SetShowSpinnerWhileLoading` is set to `true`.
  518. /// </summary>
  519. /// <param name="text">The text to display while loading indicator visible. Default is "Loading..."</param>
  520. public void SetSpinnerText(string text) {
  521. UniWebViewInterface.SetSpinnerText(listener.Name, text);
  522. }
  523. /// <summary>
  524. /// Sets whether the user can dismiss the loading indicator by tapping on it or the greyed-out background around.
  525. ///
  526. /// By default, when the loading spinner is shown, the user can dismiss it by a single tapping. Call this method
  527. /// with `false` to disable this behavior.
  528. /// </summary>
  529. /// <param name="flag">Whether the user can dismiss the loading indicator.</param>
  530. public void SetAllowUserDismissSpinner(bool flag) {
  531. UniWebViewInterface.SetAllowUserDismissSpinnerByGesture(listener.Name, flag);
  532. }
  533. /// <summary>
  534. /// Shows the loading spinner.
  535. ///
  536. /// Calling this method will show the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  537. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `true`, UniWebView will still hide
  538. /// the spinner when the loading finishes.
  539. /// </summary>
  540. public void ShowSpinner() {
  541. UniWebViewInterface.ShowSpinner(listener.Name);
  542. }
  543. /// <summary>
  544. /// Hides the loading spinner.
  545. ///
  546. /// Calling this method will hide the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  547. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `false`, UniWebView will still show
  548. /// the spinner when the loading starts.
  549. /// </summary>
  550. public void HideSpinner() {
  551. UniWebViewInterface.HideSpinner(listener.Name);
  552. }
  553. /// <summary>
  554. /// Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds.
  555. ///
  556. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  557. /// </summary>
  558. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  559. public void SetHorizontalScrollBarEnabled(bool enabled) {
  560. UniWebViewInterface.SetHorizontalScrollBarEnabled(listener.Name, enabled);
  561. }
  562. /// <summary>
  563. /// Sets whether the vertical scroll bar should show when the web content beyonds web view bounds.
  564. ///
  565. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  566. /// </summary>
  567. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  568. public void SetVerticalScrollBarEnabled(bool enabled) {
  569. UniWebViewInterface.SetVerticalScrollBarEnabled(listener.Name, enabled);
  570. }
  571. /// <summary>
  572. /// Sets whether the web view should show with a bounces effect when scrolling to page edge.
  573. ///
  574. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  575. /// </summary>
  576. /// <param name="enabled">Whether the bounces effect should be applied or not.</param>
  577. public void SetBouncesEnabled(bool enabled) {
  578. UniWebViewInterface.SetBouncesEnabled(listener.Name, enabled);
  579. }
  580. /// <summary>
  581. /// Sets whether the web view supports zoom gesture to change content size.
  582. /// Default is `false`, which means the zoom gesture is not supported.
  583. /// </summary>
  584. /// <param name="enabled">Whether the zoom gesture is allowed or not.</param>
  585. public void SetZoomEnabled(bool enabled) {
  586. UniWebViewInterface.SetZoomEnabled(listener.Name, enabled);
  587. }
  588. /// <summary>
  589. /// Sets whether the web view can receive user interaction or not.
  590. ///
  591. /// By setting this to `false`, the web view will not accept any user touch event so your users cannot tap links or
  592. /// scroll the page.
  593. ///
  594. /// </summary>
  595. /// <param name="enabled">Whether the user interaction should be enabled or not.</param>
  596. public void SetUserInteractionEnabled(bool enabled) {
  597. UniWebViewInterface.SetUserInteractionEnabled(listener.Name, enabled);
  598. }
  599. /// <summary>
  600. /// Sets whether the web view should pass through clicks at clear pixels to Unity scene.
  601. ///
  602. /// Setting this method is a pre-condition for the whole passing-through feature to work. To allow your touch passing through
  603. /// to Unity scene, the following conditions should be met at the same time:
  604. ///
  605. /// 1. This method is called with `true` and the web view accepts passing-through clicks.
  606. /// 2. The web view has a transparent background in body style for its content by CSS.
  607. /// 3. The web view itself has a transparent background color by setting `BackgroundColor` with a clear color.
  608. ///
  609. /// Then, when user clicks on the clear pixel on the web view, the touch events will not be handled by the web view.
  610. /// Instead, these events are passed to Unity scene. By using this feature, it is possible to create a native UI with the
  611. /// web view.
  612. ///
  613. /// Only clicks on transparent part on the web view will be delivered to Unity scene. The web view still intercepts
  614. /// and handles other touches on visible pixels on the web view.
  615. /// </summary>
  616. /// <param name="enabled">Whether the transparency clicking through feature should be enabled in this web view.</param>
  617. public void SetTransparencyClickingThroughEnabled(bool enabled) {
  618. UniWebViewInterface.SetTransparencyClickingThroughEnabled(listener.Name, enabled);
  619. }
  620. /// <summary>
  621. /// Refreshes the transparency clicking through layout.
  622. ///
  623. /// Call this method when the web page content changes dynamically without triggering DOM mutations that the
  624. /// automatic detection can observe. This manually triggers a re-collection of opaque regions marked with
  625. /// `data-uv-transparency="opaque"` attributes.
  626. ///
  627. /// This is useful when:
  628. /// - Content is updated programmatically without DOM changes
  629. /// - Canvas or other dynamic rendering changes opacity
  630. /// - You need to ensure the transparency regions are up-to-date
  631. ///
  632. /// This method only works when transparency clicking through is enabled. If the feature is not enabled,
  633. /// calling this method does nothing.
  634. /// </summary>
  635. /// <remarks>
  636. /// Available on both iOS and Android. Each platform refreshes the DOM-provided transparency mask immediately.
  637. /// </remarks>
  638. public void RefreshTransparencyClickingThroughLayout() {
  639. UniWebViewInterface.RefreshTransparencyClickingThroughLayout(listener.Name);
  640. }
  641. /// <summary>
  642. /// Enables user resizing for web view window. By default, you can only set the window size
  643. /// by setting its frame on mac Editor. By enabling user resizing, you would be able to resize
  644. /// the window by dragging its border as a normal macOS window.
  645. ///
  646. /// This method only works for macOS for debugging purpose. It does nothing on iOS and Android.
  647. /// </summary>
  648. /// <param name="enabled">Whether the window could be able to be resized by cursor.</param>
  649. public void SetWindowUserResizeEnabled(bool enabled) {
  650. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  651. UniWebViewInterface.SetWindowUserResizeEnabled(listener.Name, enabled);
  652. #endif
  653. }
  654. /// <summary>
  655. /// Sets whether horizontal swipe gestures should trigger back-forward list navigation.
  656. ///
  657. /// By setting with `true`, users can swipe from screen edge to perform a back or forward navigation.
  658. /// This method only works on iOS and macOS Editor. Default is `false`.
  659. ///
  660. /// On Android, the screen navigation gestures are simulating the traditional back button and it is enabled by
  661. /// default. To disable gesture navigation on Android, you have to also disable the device back button. See
  662. /// `SetBackButtonEnabled` for that purpose.
  663. /// </summary>
  664. /// <param name="flag">
  665. /// The value indicates whether a swipe gestures driven navigation should be allowed. Default is `false`.
  666. /// </param>
  667. public void SetAllowBackForwardNavigationGestures(bool flag) {
  668. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  669. UniWebViewInterface.SetAllowBackForwardNavigationGestures(listener.Name, flag);
  670. #endif
  671. }
  672. /// <summary>
  673. /// Sets the default font size used in the web view.
  674. ///
  675. /// On Android, the web view font size can be affected by the system font scale setting. Use this method to set the
  676. /// font size in a more reasonable way, by giving the web view another default font size with the system font scale
  677. /// considered. It can removes or reduces the effect of system font scale when displaying the web content.
  678. ///
  679. /// This method only works on Android. On iOS, this method does nothing since the web view will respect the font
  680. /// size setting in your CSS styles.
  681. /// </summary>
  682. /// <param name="size">The target default font size set to the web view.</param>
  683. public void SetDefaultFontSize(int size) {
  684. #if UNITY_ANDROID && !UNITY_EDITOR
  685. UniWebViewInterface.SetDefaultFontSize(listener.Name, size);
  686. #endif
  687. }
  688. /// <summary>
  689. /// Sets the text zoom used in the web view.
  690. ///
  691. /// On Android, this method call `WebSettings.setTextZoom` to the the text zoom used in the web view.
  692. ///
  693. /// This method only works on Android.
  694. /// </summary>
  695. /// <param name="textZoom">The text zoom in percent.</param>
  696. public void SetTextZoom(int textZoom) {
  697. #if UNITY_ANDROID && !UNITY_EDITOR
  698. UniWebViewInterface.SetTextZoom(listener.Name, textZoom);
  699. #endif
  700. }
  701. /// <summary>
  702. /// Scrolls the web view to a certain point.
  703. ///
  704. /// Use 0 for both `x` and `y` value to scroll the web view to its origin.
  705. /// In a normal vertical web page, it is equivalent as scrolling to top.
  706. ///
  707. /// You can use the `animated` parameter to control whether scrolling the page with or without animation.
  708. /// This parameter only works on iOS and Android. On macOS editor, the scrolling always happens without animation.
  709. /// </summary>
  710. /// <param name="x">X value of the target scrolling point.</param>
  711. /// <param name="y">Y value of the target scrolling point.</param>
  712. /// <param name="animated">If `true`, the scrolling happens with animation. Otherwise, it happens without
  713. /// animation and the content is set directly.
  714. /// </param>
  715. public void ScrollTo(int x, int y, bool animated) {
  716. UniWebViewInterface.ScrollTo(listener.Name, x, y, animated);
  717. }
  718. }