Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

2242 lignes
106 KiB

  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. /// <summary>
  21. /// Main class of UniWebView. Any `GameObject` instance with this script can represent a webview object in the scene.
  22. /// Use this class to create, load, show and interact with a general-purpose web view.
  23. /// </summary>
  24. public class UniWebView: MonoBehaviour {
  25. /// <summary>
  26. /// Delegate for page started event.
  27. /// </summary>
  28. /// <param name="webView">The web view component which raises this event.</param>
  29. /// <param name="url">The url which the web view is about to load.</param>
  30. public delegate void PageStartedDelegate(UniWebView webView, string url);
  31. /// <summary>
  32. /// Raised when the web view starts loading a url.
  33. ///
  34. /// This event will be invoked for both url loading with `Load` method or by a link navigating from page.
  35. /// </summary>
  36. public event PageStartedDelegate OnPageStarted;
  37. /// <summary>
  38. /// Delegate for page finished event.
  39. /// </summary>
  40. /// <param name="webView">The web view component which raises this event.</param>
  41. /// <param name="statusCode">HTTP status code received from response.</param>
  42. /// <param name="url">The url which the web view loaded.</param>
  43. public delegate void PageFinishedDelegate(UniWebView webView, int statusCode, string url);
  44. /// <summary>
  45. /// Raised when the web view finished to load a url successfully.
  46. ///
  47. /// This method will be invoked when a valid response received from the url, regardless of the response status.
  48. /// If a url loading fails before reaching to the server and getting a response, `OnLoadingErrorReceived` will be
  49. /// raised instead.
  50. /// </summary>
  51. public event PageFinishedDelegate OnPageFinished;
  52. /// <summary>
  53. /// Delegate for page error received event.
  54. ///
  55. /// Deprecated. Use `LoadingErrorReceivedDelegate` instead.
  56. /// </summary>
  57. /// <param name="webView">The web view component which raises this event.</param>
  58. /// <param name="errorCode">
  59. /// The error code which indicates the error type.
  60. /// It can be different from systems and platforms.
  61. /// </param>
  62. /// <param name="errorMessage">The error message which indicates the error.</param>
  63. [Obsolete("PageErrorReceivedDelegate is deprecated. Use `LoadingErrorReceivedDelegate` instead.", false)]
  64. public delegate void PageErrorReceivedDelegate(UniWebView webView, int errorCode, string errorMessage);
  65. /// <summary>
  66. /// Raised when an error encountered during the loading process.
  67. /// Such as the "host not found" error or "no Internet connection" error will raise this event.
  68. ///
  69. /// Deprecated. Use `OnLoadingErrorReceived` instead. If both `OnPageErrorReceived` and `OnLoadingErrorReceived` are
  70. /// listened, only the new `OnLoadingErrorReceived` will be raised, `OnPageErrorReceived` will not be called.
  71. /// </summary>
  72. [Obsolete("OnPageErrorReceived is deprecated. Use `OnLoadingErrorReceived` instead.", false)]
  73. public event PageErrorReceivedDelegate OnPageErrorReceived;
  74. /// <summary>
  75. /// Delegate for page loading error received event.
  76. /// </summary>
  77. /// <param name="webView">The web view component which raises this event.</param>
  78. /// <param name="errorCode">
  79. /// The error code which indicates the error type.
  80. /// It can be different from systems and platforms.
  81. /// </param>
  82. /// <param name="errorMessage">The error message which indicates the error.</param>
  83. /// <param name="payload">The payload received from native side, which contains the error information, such as the failing URL, in its `Extra`.</param>
  84. public delegate void LoadingErrorReceivedDelegate(
  85. UniWebView webView,
  86. int errorCode,
  87. string errorMessage,
  88. UniWebViewNativeResultPayload payload);
  89. /// <summary>
  90. /// Raised when an error encountered during the loading process.
  91. /// Such as the "host not found" error or "no Internet connection" error will raise this event.
  92. ///
  93. /// </summary>
  94. public event LoadingErrorReceivedDelegate OnLoadingErrorReceived;
  95. /// <summary>
  96. /// Delegate for page progress changed event.
  97. /// </summary>
  98. /// <param name="webView">The web view component which raises this event.</param>
  99. /// <param name="progress">A value indicates the loading progress of current page. It is a value between 0.0f and 1.0f.</param>
  100. public delegate void PageProgressChangedDelegate(UniWebView webView, float progress);
  101. /// <summary>
  102. /// Raised when the loading progress value changes in current web view.
  103. /// </summary>
  104. public event PageProgressChangedDelegate OnPageProgressChanged;
  105. /// <summary>
  106. /// Delegate for message received event.
  107. /// </summary>
  108. /// <param name="webView">The web view component which raises this event.</param>
  109. /// <param name="message">Message received from web view.</param>
  110. public delegate void MessageReceivedDelegate(UniWebView webView, UniWebViewMessage message);
  111. /// <summary>
  112. /// Raised when a message from web view is received.
  113. ///
  114. /// Generally, the message comes from a navigation to
  115. /// a scheme which is observed by current web view. You could use `AddUrlScheme` and
  116. /// `RemoveUrlScheme` to manipulate the scheme list.
  117. ///
  118. /// "uniwebview://" scheme is default in the list, so a clicking on link starting with "uniwebview://"
  119. /// will raise this event, if it is not removed.
  120. /// </summary>
  121. public event MessageReceivedDelegate OnMessageReceived;
  122. /// <summary>
  123. /// Delegate for should close event.
  124. /// </summary>
  125. /// <param name="webView">The web view component which raises this event.</param>
  126. /// <returns>Whether the web view should be closed and destroyed.</returns>
  127. public delegate bool ShouldCloseDelegate(UniWebView webView);
  128. /// <summary>
  129. /// Raised when the web view is about to close itself.
  130. ///
  131. /// This event is raised when the users close the web view by Back button on Android, Done button on iOS,
  132. /// or Close button on Unity Editor. It gives a chance to make final decision whether the web view should
  133. /// be closed and destroyed. You can also clean all related resources you created (such as a reference to
  134. /// the web view) in this event.
  135. /// </summary>
  136. public event ShouldCloseDelegate OnShouldClose;
  137. /// <summary>
  138. /// Delegate for orientation changed event.
  139. /// </summary>
  140. /// <param name="webView">The web view component which raises this event.</param>
  141. /// <param name="orientation">The screen orientation for current state.</param>
  142. public delegate void OrientationChangedDelegate(UniWebView webView, ScreenOrientation orientation);
  143. /// <summary>
  144. /// Raised when the screen orientation is changed. It is a good time to set the web view frame if you
  145. /// need to support multiple orientations in your game.
  146. /// </summary>
  147. public event OrientationChangedDelegate OnOrientationChanged;
  148. /// <summary>
  149. /// Delegate for content loading terminated event.
  150. /// </summary>
  151. /// <param name="webView">The web view component which raises this event.</param>
  152. public delegate void OnWebContentProcessTerminatedDelegate(UniWebView webView);
  153. /// <summary>
  154. /// On iOS, raise when the system calls `webViewWebContentProcessDidTerminate` method. On Android, raise when the
  155. /// system calls `onRenderProcessGone` method.
  156. ///
  157. /// It is usually due to a low memory or the render process crashes when loading the web content. When this happens,
  158. /// the web view will leave you a blank white screen.
  159. ///
  160. /// Usually you should close the web view and clean all the resource since there is no good way to restore. In some
  161. /// cases, you can also try to free as much as memory and do a page `Reload`.
  162. /// </summary>
  163. public event OnWebContentProcessTerminatedDelegate OnWebContentProcessTerminated;
  164. /// <summary>
  165. /// Delegate for file download task starting event.
  166. /// </summary>
  167. /// <param name="webView">The web view component which raises this event.</param>
  168. /// <param name="remoteUrl">The remote URL of this download task. This is also the download URL for the task.</param>
  169. /// <param name="fileName">The file name which user chooses to use.</param>
  170. public delegate void FileDownloadStarted(UniWebView webView, string remoteUrl, string fileName);
  171. /// <summary>
  172. /// Raised when a file download task starts.
  173. /// </summary>
  174. public event FileDownloadStarted OnFileDownloadStarted;
  175. /// <summary>
  176. /// Delegate for file download task finishing event.
  177. /// </summary>
  178. /// <param name="webView">The web view component which raises this event.</param>
  179. /// <param name="errorCode">
  180. /// The error code of the download task result. Value `0` means the download finishes without a problem.
  181. /// Any other non-`0` value indicates an issue. The detail meaning of the error code depends on system.
  182. /// On iOS, it is usually the `errorCode` of the received `NSURLError`. On Android, the value usually represents
  183. /// an `ERROR_*` value in `DownloadManager`.
  184. /// </param>
  185. /// <param name="remoteUrl">The remote URL of this download task.</param>
  186. /// <param name="diskPath">
  187. /// The file path of the downloaded file. On iOS, the downloader file is in a temporary folder of your app sandbox.
  188. /// On Android, it is in the "Download" folder of your app.
  189. /// </param>
  190. public delegate void FileDownloadFinished(UniWebView webView, int errorCode, string remoteUrl, string diskPath);
  191. /// <summary>
  192. /// Raised when a file download task finishes with either an error or success.
  193. /// </summary>
  194. public event FileDownloadFinished OnFileDownloadFinished;
  195. /// <summary>
  196. /// Delegate for capturing snapshot finished event.
  197. /// </summary>
  198. /// <param name="webView">The web view component which raises this event.</param>
  199. /// <param name="errorCode">
  200. /// The error code of the event. If the snapshot is captured and stored without a problem, the error code is 0.
  201. /// Any other number indicates an error happened. In most cases, the screenshot capturing only fails due to lack
  202. /// of disk storage.
  203. /// </param>
  204. /// <param name="diskPath">
  205. /// An accessible disk path to the captured snapshot image. If an error happens, it is an empty string.
  206. /// </param>
  207. public delegate void CaptureSnapshotFinished(UniWebView webView, int errorCode, string diskPath);
  208. /// <summary>
  209. /// Raised when an image captured and stored in a cache path on disk.
  210. /// </summary>
  211. public event CaptureSnapshotFinished OnCaptureSnapshotFinished;
  212. /// <summary>
  213. /// Delegate for multiple window opening event.
  214. /// </summary>
  215. /// <param name="webView">The web view component which opens the new multiple (pop-up) window.</param>
  216. /// <param name="multipleWindowId">The identifier of the opened new window.</param>
  217. public delegate void MultipleWindowOpenedDelegate(UniWebView webView, string multipleWindowId);
  218. /// <summary>
  219. /// Raised when a new window is opened. This happens when you enable the `SetSupportMultipleWindows` and open a
  220. /// new pop-up window.
  221. /// </summary>
  222. public event MultipleWindowOpenedDelegate OnMultipleWindowOpened;
  223. /// <summary>
  224. /// Delegate for multiple window closing event.
  225. /// </summary>
  226. /// <param name="webView">The web view component which closes the multiple window.</param>
  227. /// <param name="multipleWindowId">The identifier of the closed window.</param>
  228. public delegate void MultipleWindowClosedDelegate(UniWebView webView, string multipleWindowId);
  229. /// <summary>
  230. /// Raised when the multiple window is closed. This happens when the pop-up window is closed by navigation operation
  231. /// or by a invocation of `close()` on the page.
  232. /// </summary>
  233. public event MultipleWindowClosedDelegate OnMultipleWindowClosed;
  234. private static readonly Rect snapshotFullViewRect = new Rect(-1, -1, -1, -1);
  235. private string id = Guid.NewGuid().ToString();
  236. private UniWebViewNativeListener listener;
  237. /// <summary>
  238. /// Represents the embedded toolbar in the current web view.
  239. /// </summary>
  240. public UniWebViewEmbeddedToolbar EmbeddedToolbar { get; private set; }
  241. private ScreenOrientation currentOrientation;
  242. [SerializeField]
  243. #pragma warning disable 0649
  244. private string urlOnStart;
  245. [SerializeField]
  246. private bool showOnStart = false;
  247. [SerializeField]
  248. private bool fullScreen;
  249. [Obsolete("Use Toolbar is deprecated. Use the embedded toolbar instead.", false)]
  250. [SerializeField]
  251. private bool useToolbar;
  252. [Obsolete("Use Toolbar is deprecated. Use the embedded toolbar instead.", false)]
  253. [SerializeField]
  254. private UniWebViewToolbarPosition toolbarPosition;
  255. [SerializeField]
  256. private bool useEmbeddedToolbar;
  257. [SerializeField]
  258. private UniWebViewToolbarPosition embeddedToolbarPosition;
  259. #pragma warning restore 0649
  260. // Action callback holders
  261. private Dictionary<String, Action> actions = new Dictionary<String, Action>();
  262. private Dictionary<String, Action<UniWebViewNativeResultPayload>> payloadActions = new Dictionary<String, Action<UniWebViewNativeResultPayload>>();
  263. [SerializeField]
  264. private Rect frame;
  265. /// <summary>
  266. /// Gets or sets the frame of current web view. The value is based on current `Screen.width` and `Screen.height`.
  267. /// The first two values of `Rect` is `x` and `y` position and the followed two `width` and `height`.
  268. /// </summary>
  269. public Rect Frame {
  270. get => frame;
  271. set {
  272. frame = value;
  273. UpdateFrame();
  274. }
  275. }
  276. [SerializeField]
  277. private RectTransform referenceRectTransform;
  278. /// <summary>
  279. /// A reference rect transform which the web view should change its position and size to.
  280. /// Set it to a Unity UI element (which contains a `RectTransform`) under a canvas to determine
  281. /// the web view frame by a certain UI element.
  282. ///
  283. /// By using this, you could get benefit from [Multiple Resolutions UI](https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html).
  284. ///
  285. /// </summary>
  286. public RectTransform ReferenceRectTransform {
  287. get => referenceRectTransform;
  288. set {
  289. referenceRectTransform = value;
  290. UpdateFrame();
  291. }
  292. }
  293. private bool started;
  294. private bool backButtonEnabled = true;
  295. /// <summary>
  296. /// The url of current loaded web page.
  297. /// </summary>
  298. public string Url => UniWebViewInterface.GetUrl(listener.Name);
  299. /// <summary>
  300. /// Updates and sets current frame of web view to match the setting.
  301. ///
  302. /// This is useful if the `referenceRectTransform` is changed and you need to sync the frame change
  303. /// to the web view. This method follows the frame determining rules.
  304. /// </summary>
  305. public void UpdateFrame() {
  306. Rect rect = NextFrameRect();
  307. // Sync web view frame property.
  308. frame = rect;
  309. UniWebViewInterface.SetFrame(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
  310. }
  311. Rect NextFrameRect()
  312. {
  313. if (referenceRectTransform == null) {
  314. UniWebViewLogger.Instance.Info("Using Frame setting to determine web view frame.");
  315. return frame;
  316. }
  317. UniWebViewLogger.Instance.Info("Using reference RectTransform to determine web view frame.");
  318. var worldCorners = new Vector3[4];
  319. referenceRectTransform.GetWorldCorners(worldCorners);
  320. // var bottomLeft = worldCorners[0];
  321. var topLeft = worldCorners[1];
  322. // var topRight = worldCorners[2];
  323. var bottomRight = worldCorners[3];
  324. var canvas = referenceRectTransform.GetComponentInParent<Canvas>();
  325. if (canvas == null) {
  326. return frame;
  327. }
  328. switch (canvas.renderMode) {
  329. case RenderMode.ScreenSpaceOverlay:
  330. break;
  331. case RenderMode.ScreenSpaceCamera:
  332. case RenderMode.WorldSpace:
  333. var camera = canvas.worldCamera;
  334. if (camera == null) {
  335. UniWebViewLogger.Instance.Critical(@"You need a render camera
  336. or event camera to use RectTransform to determine correct
  337. frame for UniWebView.");
  338. UniWebViewLogger.Instance.Info("No camera found. Fall back to ScreenSpaceOverlay mode.");
  339. } else {
  340. // bottomLeft = camera.WorldToScreenPoint(bottomLeft);
  341. topLeft = camera.WorldToScreenPoint(topLeft);
  342. // topRight = camera.WorldToScreenPoint(topRight);
  343. bottomRight = camera.WorldToScreenPoint(bottomRight);
  344. }
  345. break;
  346. default:
  347. throw new ArgumentOutOfRangeException();
  348. }
  349. var widthFactor = UniWebViewInterface.NativeScreenWidth() / Screen.width;
  350. var heightFactor = UniWebViewInterface.NativeScreenHeight() / Screen.height;
  351. var x = topLeft.x * widthFactor;
  352. var y = (Screen.height - topLeft.y) * heightFactor;
  353. var width = (bottomRight.x - topLeft.x) * widthFactor;
  354. var height = (topLeft.y - bottomRight.y) * heightFactor;
  355. return new Rect(x, y, width, height);
  356. }
  357. void Awake() {
  358. var listenerObject = new GameObject(id);
  359. listener = listenerObject.AddComponent<UniWebViewNativeListener>();
  360. listenerObject.transform.parent = transform;
  361. listener.webView = this;
  362. UniWebViewNativeListener.AddListener(listener);
  363. EmbeddedToolbar = new UniWebViewEmbeddedToolbar(listener);
  364. var rect = fullScreen ? new Rect(0, 0, Screen.width, Screen.height) : NextFrameRect();
  365. UniWebViewInterface.Init(listener.Name, (int)rect.x, (int)rect. y, (int)rect.width, (int)rect.height);
  366. currentOrientation = Screen.orientation;
  367. }
  368. void Start() {
  369. if (showOnStart) {
  370. Show();
  371. }
  372. if (useEmbeddedToolbar) {
  373. EmbeddedToolbar.SetPosition(embeddedToolbarPosition);
  374. EmbeddedToolbar.Show();
  375. }
  376. if (!string.IsNullOrEmpty(urlOnStart)) {
  377. Load(urlOnStart);
  378. }
  379. started = true;
  380. if (referenceRectTransform != null) {
  381. UpdateFrame();
  382. }
  383. }
  384. void Update() {
  385. var newOrientation = Screen.orientation;
  386. if (currentOrientation != newOrientation) {
  387. currentOrientation = newOrientation;
  388. if (OnOrientationChanged != null) {
  389. OnOrientationChanged(this, newOrientation);
  390. }
  391. if (referenceRectTransform != null) {
  392. UpdateFrame();
  393. }
  394. }
  395. // 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
  396. //
  397. // The new input system is not handling touchscreen events nicely as the old one.
  398. // The gesture detection hangs out regularly. Wait for an improvement of Unity.
  399. // So we choose to use the old one whenever it is available.
  400. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  401. var backDetected = backButtonEnabled && UnityEngine.InputSystem.Keyboard.current.escapeKey.wasPressedThisFrame;
  402. #else
  403. var backDetected = backButtonEnabled && Input.GetKeyUp(KeyCode.Escape);
  404. #endif
  405. if (backDetected) {
  406. UniWebViewLogger.Instance.Info("Received Back button, handling GoBack or close web view.");
  407. if (CanGoBack) {
  408. GoBack();
  409. } else {
  410. InternalOnShouldClose();
  411. }
  412. }
  413. }
  414. void OnEnable() {
  415. if (started) {
  416. _Show(useAsync: true);
  417. }
  418. }
  419. void OnDisable() {
  420. if (started) {
  421. _Hide(useAsync: true);
  422. }
  423. }
  424. /// <summary>
  425. /// Whether the web view is supported in current runtime or not.
  426. ///
  427. /// On some certain Android customized builds, the manufacturer prefers not containing the web view package in the
  428. /// system or blocks the web view package from being installed. If this happens, using of any web view related APIs will
  429. /// throw a `MissingWebViewPackageException` exception.
  430. ///
  431. /// Use this method to check whether the web view is available on the current running system. If this parameter returns `false`,
  432. /// you should not use the web view.
  433. ///
  434. /// This property always returns `true` on other supported platforms, such as iOS or macOS editor. It only performs
  435. /// runtime checking on Android. On other not supported platforms such as Windows or Linux, it always returns `false`.
  436. /// </summary>
  437. /// <value>Returns `true` if web view is supported on the current platform. Otherwise, `false`.</value>
  438. public static bool IsWebViewSupported {
  439. get {
  440. #if UNITY_EDITOR_OSX
  441. return true;
  442. #elif UNITY_EDITOR
  443. return false;
  444. #elif UNITY_IOS
  445. return true;
  446. #elif UNITY_STANDALONE_OSX
  447. return true;
  448. #elif UNITY_ANDROID
  449. return UniWebViewInterface.IsWebViewSupported();
  450. #else
  451. return false;
  452. #endif
  453. }
  454. }
  455. /// <summary>
  456. /// Sets whether this web view instance should try to restore its view hierarchy when resumed.
  457. ///
  458. /// In some versions of Unity when running on Android, the player view is brought to front when switching back
  459. /// from a pause state, which causes the web view is invisible when the app is resumed. It requires an additional
  460. /// step to bring the web view to front to make the web view visible. Set this to true to apply this workaround.
  461. ///
  462. /// Issue caused by:
  463. /// 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
  464. ///
  465. /// This issue is known in these released versions:
  466. /// - Unity 2021.3.31, 2021.3.32, 2021.3.31, 2021.3.34
  467. /// - Unity 2022.3.10, 2022.3.11, 2022.3.12, 2022.3.13, 2022.3.14, 2022.3.15
  468. ///
  469. /// If you are using UniWebView in these versions, you may want to set this value to `true`.
  470. /// </summary>
  471. public bool RestoreViewHierarchyOnResume { get; set; }
  472. /// <summary>
  473. /// Loads a url in current web view.
  474. /// </summary>
  475. /// <param name="url">The url to be loaded. This url should start with `http://` or `https://` scheme. You could even load a non-ascii url text if it is valid.</param>
  476. /// <param name="skipEncoding">
  477. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  478. /// loading it. Otherwise, your original url string will be used as the url if it is valid. Default is `false`.
  479. /// </param>
  480. /// <param name="readAccessURL">
  481. /// The URL to allow read access to. This parameter is only used when loading from the filesystem in iOS, and passed
  482. /// to `loadFileURL:allowingReadAccessToURL:` method of WebKit. By default, the parent folder of the `url` parameter will be read accessible.
  483. /// </param>
  484. public void Load(string url, bool skipEncoding = false, string readAccessURL = null) {
  485. UniWebViewInterface.Load(listener.Name, url, skipEncoding, readAccessURL);
  486. }
  487. /// <summary>
  488. /// Loads an HTML string in current web view.
  489. /// </summary>
  490. /// <param name="htmlString">The HTML string to use as the contents of the webpage.</param>
  491. /// <param name="baseUrl">The url to use as the page's base url.</param>
  492. /// <param name="skipEncoding">
  493. /// Whether UniWebView should skip encoding the baseUrl or not. If set to `false`, UniWebView will try to encode the baseUrl parameter before
  494. /// using it. Otherwise, your original url string will be used as the baseUrl if it is valid. Default is `false`.
  495. /// </param>
  496. public void LoadHTMLString(string htmlString, string baseUrl, bool skipEncoding = false) {
  497. UniWebViewInterface.LoadHTMLString(listener.Name, htmlString, baseUrl, skipEncoding);
  498. }
  499. /// <summary>
  500. /// Reloads the current page.
  501. /// </summary>
  502. public void Reload() {
  503. UniWebViewInterface.Reload(listener.Name);
  504. }
  505. /// <summary>
  506. /// Stops loading all resources on the current page.
  507. /// </summary>
  508. public void Stop() {
  509. UniWebViewInterface.Stop(listener.Name);
  510. }
  511. /// <summary>
  512. /// Gets whether there is a back page in the back-forward list that can be navigated to.
  513. /// </summary>
  514. public bool CanGoBack => UniWebViewInterface.CanGoBack(listener.Name);
  515. /// <summary>
  516. /// Gets whether there is a forward page in the back-forward list that can be navigated to.
  517. /// </summary>
  518. public bool CanGoForward => UniWebViewInterface.CanGoForward(listener.Name);
  519. /// <summary>
  520. /// Navigates to the back item in the back-forward list.
  521. /// </summary>
  522. public void GoBack() {
  523. UniWebViewInterface.GoBack(listener.Name);
  524. }
  525. /// <summary>
  526. /// Navigates to the forward item in the back-forward list.
  527. /// </summary>
  528. public void GoForward() {
  529. UniWebViewInterface.GoForward(listener.Name);
  530. }
  531. /// <summary>
  532. /// Sets whether the link clicking in the web view should open the page in an external browser.
  533. /// </summary>
  534. /// <param name="flag">The flag indicates whether a link should be opened externally.</param>
  535. public void SetOpenLinksInExternalBrowser(bool flag) {
  536. UniWebViewInterface.SetOpenLinksInExternalBrowser(listener.Name, flag);
  537. }
  538. /// <summary>
  539. /// Sets the web view visible on screen.
  540. ///
  541. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  542. /// be applied when showing. So the `duration` parameter will not be taken into account. Otherwise, when
  543. /// either or both `fade` and `edge` set, the showing operation will be animated.
  544. ///
  545. /// Regardless of there is an animation or not, the `completionHandler` will be called if not `null` when the web
  546. /// view showing finishes.
  547. /// </summary>
  548. /// <param name="fade">Whether show with a fade in animation. Default is `false`.</param>
  549. /// <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>
  550. /// <param name="duration">Duration of the showing animation. Default is `0.4f`.</param>
  551. /// <param name="completionHandler">Completion handler which will be called when showing finishes. Default is `null`.</param>
  552. /// <returns>A bool value indicates whether the showing operation started.</returns>
  553. public bool Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  554. float duration = 0.4f, Action completionHandler = null)
  555. {
  556. return _Show(fade, edge, duration, false, completionHandler);
  557. }
  558. public bool _Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  559. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  560. {
  561. var identifier = Guid.NewGuid().ToString();
  562. var showStarted = UniWebViewInterface.Show(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  563. if (showStarted && completionHandler != null) {
  564. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  565. if (hasAnimation) {
  566. actions.Add(identifier, completionHandler);
  567. } else {
  568. completionHandler();
  569. }
  570. }
  571. #pragma warning disable 618
  572. if (showStarted && useToolbar) {
  573. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  574. SetShowToolbar(true, false, top, fullScreen);
  575. }
  576. #pragma warning restore 618
  577. return showStarted;
  578. }
  579. /// <summary>
  580. /// Sets the web view invisible from screen.
  581. ///
  582. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  583. /// be applied when hiding. So the `duration` parameter will not be taken into account. Otherwise, when either or
  584. /// both `fade` and `edge` set, the hiding operation will be animated.
  585. ///
  586. /// Regardless there is an animation or not, the `completionHandler` will be called if not `null` when the web view
  587. /// hiding finishes.
  588. /// </summary>
  589. /// <param name="fade">Whether hide with a fade in animation. Default is `false`.</param>
  590. /// <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>
  591. /// <param name="duration">Duration of hiding animation. Default is `0.4f`.</param>
  592. /// <param name="completionHandler">Completion handler which will be called when hiding finishes. Default is `null`.</param>
  593. /// <returns>A bool value indicates whether the hiding operation started.</returns>
  594. public bool Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  595. float duration = 0.4f, Action completionHandler = null)
  596. {
  597. return _Hide(fade, edge, duration, false, completionHandler);
  598. }
  599. public bool _Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  600. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  601. {
  602. var identifier = Guid.NewGuid().ToString();
  603. var hideStarted = UniWebViewInterface.Hide(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  604. if (hideStarted && completionHandler != null) {
  605. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  606. if (hasAnimation) {
  607. actions.Add(identifier, completionHandler);
  608. } else {
  609. completionHandler();
  610. }
  611. }
  612. #pragma warning disable 618
  613. if (hideStarted && useToolbar) {
  614. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  615. SetShowToolbar(false, false, top, fullScreen);
  616. }
  617. #pragma warning restore 618
  618. return hideStarted;
  619. }
  620. /// <summary>
  621. /// Animates the web view from current position and size to another position and size.
  622. /// </summary>
  623. /// <param name="frame">The new `Frame` which the web view should be.</param>
  624. /// <param name="duration">Duration of the animation.</param>
  625. /// <param name="delay">Delay before the animation begins. Default is `0.0f`, which means the animation will start immediately.</param>
  626. /// <param name="completionHandler">Completion handler which will be called when animation finishes. Default is `null`.</param>
  627. /// <returns></returns>
  628. public bool AnimateTo(Rect frame, float duration, float delay = 0.0f, Action completionHandler = null) {
  629. var identifier = Guid.NewGuid().ToString();
  630. var animationStarted = UniWebViewInterface.AnimateTo(listener.Name,
  631. (int)frame.x, (int)frame.y, (int)frame.width, (int)frame.height, duration, delay, identifier);
  632. if (animationStarted) {
  633. this.frame = frame;
  634. if (completionHandler != null) {
  635. actions.Add(identifier, completionHandler);
  636. }
  637. }
  638. return animationStarted;
  639. }
  640. /// <summary>
  641. /// Adds a JavaScript to current page.
  642. /// </summary>
  643. /// <param name="jsString">The JavaScript code to add. It should be a valid JavaScript statement string.</param>
  644. /// <param name="completionHandler">Called when adding JavaScript operation finishes. Default is `null`.</param>
  645. public void AddJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  646. var identifier = Guid.NewGuid().ToString();
  647. UniWebViewInterface.AddJavaScript(listener.Name, jsString, identifier);
  648. if (completionHandler != null) {
  649. payloadActions.Add(identifier, completionHandler);
  650. }
  651. }
  652. /// <summary>
  653. /// Evaluates a JavaScript string on current page.
  654. /// </summary>
  655. /// <param name="jsString">The JavaScript string to evaluate.</param>
  656. /// <param name="completionHandler">Called when evaluating JavaScript operation finishes. Default is `null`.</param>
  657. public void EvaluateJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  658. var identifier = Guid.NewGuid().ToString();
  659. UniWebViewInterface.EvaluateJavaScript(listener.Name, jsString, identifier);
  660. if (completionHandler != null) {
  661. payloadActions.Add(identifier, completionHandler);
  662. }
  663. }
  664. /// <summary>
  665. /// Adds a url scheme to UniWebView message system interpreter.
  666. /// All following url navigation to this scheme will be sent as a message to UniWebView instead.
  667. /// </summary>
  668. /// <param name="scheme">The url scheme to add. It should not contain "://" part. You could even add "http" and/or
  669. /// "https" to prevent all resource loading on the page. "uniwebview" is added by default. Nothing will happen if
  670. /// you try to add a duplicated scheme.</param>
  671. public void AddUrlScheme(string scheme) {
  672. if (scheme == null) {
  673. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  674. return;
  675. }
  676. if (scheme.Contains("://")) {
  677. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  678. return;
  679. }
  680. UniWebViewInterface.AddUrlScheme(listener.Name, scheme);
  681. }
  682. /// <summary>
  683. /// Removes a url scheme from UniWebView message system interpreter.
  684. /// </summary>
  685. /// <param name="scheme">The url scheme to remove. Nothing will happen if the scheme is not in the message system.</param>
  686. public void RemoveUrlScheme(string scheme) {
  687. if (scheme == null) {
  688. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  689. return;
  690. }
  691. if (scheme.Contains("://")) {
  692. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  693. return;
  694. }
  695. UniWebViewInterface.RemoveUrlScheme(listener.Name, scheme);
  696. }
  697. /// <summary>
  698. /// Adds a domain to the SSL checking white list.
  699. /// If you are trying to access a web site with untrusted or expired certification,
  700. /// the web view will prevent its loading. If you could confirm that this site is trusted,
  701. /// you can add the domain as an SSL exception, so you could visit it.
  702. /// </summary>
  703. /// <param name="domain">The domain to add. It should not contain any scheme or path part in url.</param>
  704. public void AddSslExceptionDomain(string domain) {
  705. if (domain == null) {
  706. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  707. return;
  708. }
  709. if (domain.Contains("://")) {
  710. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  711. return;
  712. }
  713. UniWebViewInterface.AddSslExceptionDomain(listener.Name, domain);
  714. }
  715. /// <summary>
  716. /// Removes a domain from the SSL checking white list.
  717. /// </summary>
  718. /// <param name="domain">The domain to remove. It should not contain any scheme or path part in url.</param>
  719. public void RemoveSslExceptionDomain(string domain) {
  720. if (domain == null) {
  721. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  722. return;
  723. }
  724. if (domain.Contains("://")) {
  725. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  726. return;
  727. }
  728. UniWebViewInterface.RemoveSslExceptionDomain(listener.Name, domain);
  729. }
  730. /// <summary>
  731. /// Sets a customized header field for web view requests.
  732. ///
  733. /// The header field will be used for all subsequence request.
  734. /// Pass `null` as value to unset a header field.
  735. ///
  736. /// Some reserved headers like user agent are not be able to override by setting here,
  737. /// use the `SetUserAgent` method for them instead.
  738. /// </summary>
  739. /// <param name="key">The key of customized header field.</param>
  740. /// <param name="value">The value of customized header field. `null` if you want to unset the field.</param>
  741. public void SetHeaderField(string key, string value) {
  742. if (key == null) {
  743. UniWebViewLogger.Instance.Critical("Header key should not be null.");
  744. return;
  745. }
  746. UniWebViewInterface.SetHeaderField(listener.Name, key, value);
  747. }
  748. /// <summary>
  749. /// Sets the user agent used in the web view.
  750. /// If the string is null or empty, the system default value will be used.
  751. /// </summary>
  752. /// <param name="agent">The new user agent string to use.</param>
  753. public void SetUserAgent(string agent) {
  754. UniWebViewInterface.SetUserAgent(listener.Name, agent);
  755. }
  756. /// <summary>
  757. /// Gets the user agent string currently used in web view.
  758. /// If a customized user agent is not set, the default user agent in current platform will be returned.
  759. /// </summary>
  760. /// <returns>The user agent string in use.</returns>
  761. public string GetUserAgent() {
  762. return UniWebViewInterface.GetUserAgent(listener.Name);
  763. }
  764. /// <summary>
  765. /// Sets the adjustment behavior which indicates how safe area insets
  766. /// are added to the adjusted content inset. It is a wrapper of `contentInsetAdjustmentBehavior` on iOS.
  767. ///
  768. /// It only works on iOS 11 and above. You need to call this method as soon as you create a web view,
  769. /// before you call any other methods related to web view layout (like `Show` or `SetShowToolbar`).
  770. /// </summary>
  771. /// <param name="behavior">The behavior for determining the adjusted content offsets.</param>
  772. public void SetContentInsetAdjustmentBehavior(
  773. UniWebViewContentInsetAdjustmentBehavior behavior
  774. )
  775. {
  776. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  777. UniWebViewInterface.SetContentInsetAdjustmentBehavior(listener.Name, behavior);
  778. #endif
  779. }
  780. /// <summary>
  781. /// Sets allow auto play for current web view. By default,
  782. /// users need to touch the play button to start playing a media resource.
  783. ///
  784. /// By setting this to `true`, you can start the playing automatically through
  785. /// corresponding media tag attributes.
  786. /// </summary>
  787. /// <param name="flag">A flag indicates whether autoplaying of media is allowed or not.</param>
  788. public static void SetAllowAutoPlay(bool flag) {
  789. UniWebViewInterface.SetAllowAutoPlay(flag);
  790. }
  791. /// <summary>
  792. /// Sets allow inline play for current web view. By default, on iOS, the video
  793. /// can only be played in a new full screen view.
  794. /// By setting this to `true`, you could play a video inline the page, instead of opening
  795. /// a new full screen window.
  796. ///
  797. /// This only works for iOS and macOS Editor.
  798. /// On Android, you could play videos inline by default and calling this method does nothing.
  799. /// </summary>
  800. /// <param name="flag">A flag indicates whether inline playing of media is allowed or not.</param>
  801. public static void SetAllowInlinePlay(bool flag) {
  802. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  803. UniWebViewInterface.SetAllowInlinePlay(flag);
  804. #endif
  805. }
  806. /// <summary>
  807. /// Sets whether loading a local file is allowed.
  808. ///
  809. /// If set to `false`, any load from a file URL `file://` for `Load` method will be rejected and trigger an
  810. /// `OnLoadingErrorReceived` event. That means you cannot load a web page from any local file. If you do not going to
  811. /// load any local files, setting it to `false` helps to reduce the interface of web view and improve the security.
  812. ///
  813. /// By default, it is `true` and the local file URL loading is allowed.
  814. /// </summary>
  815. /// <param name="flag">Whether the local file access by web view loading is allowed or not.</param>
  816. public void SetAllowFileAccess(bool flag) {
  817. UniWebViewInterface.SetAllowFileAccess(listener.Name, flag);
  818. }
  819. /// <summary>
  820. /// Sets whether file access from file URLs is allowed.
  821. ///
  822. /// By setting with `true`, access to file URLs inside the web view will be enabled and you could access
  823. /// sub-resources or make cross origin requests from local HTML files.
  824. ///
  825. /// On iOS, it uses some "hidden" way by setting `allowFileAccessFromFileURLs` in config preferences for WebKit.
  826. /// So it is possible that it stops working in a future version.
  827. ///
  828. /// On Android, it sets the `WebSettings.setAllowFileAccessFromFileURLs` for the current web view.
  829. /// </summary>
  830. /// <param name="flag">Whether the file access inside web view from file URLs is allowed or not.</param>
  831. public void SetAllowFileAccessFromFileURLs(bool flag) {
  832. UniWebViewInterface.SetAllowFileAccessFromFileURLs(listener.Name, flag);
  833. }
  834. /// <summary>
  835. /// Sets whether the UniWebView should allow third party cookies to be set. By default, on Android, the third party
  836. /// cookies are disallowed due to security reason. Setting this to `true` will allow the cookie manager to accept
  837. /// third party cookies you set.
  838. ///
  839. /// This method only works for Android. On iOS, this method does nothing and the third party cookies are always
  840. /// allowed.
  841. /// </summary>
  842. /// <param name="flag">Whether the third party cookies should be allowed.</param>
  843. public void SetAcceptThirdPartyCookies(bool flag) {
  844. #if UNITY_ANDROID && !UNITY_EDITOR
  845. UniWebViewInterface.SetAcceptThirdPartyCookies(listener.Name, flag);
  846. #endif
  847. }
  848. /// <summary>
  849. /// Sets allow universal access from file URLs. By default, on iOS, the `WKWebView` forbids any load of local files
  850. /// through AJAX even when opening a local HTML file. It checks the CORS rules and fails at web view level.
  851. /// This is useful when you want access these files by setting the `allowUniversalAccessFromFileURLs` key of web view
  852. /// configuration.
  853. ///
  854. /// On iOS and macOS Editor. It uses some "hidden" way by setting `allowUniversalAccessFromFileURLs` in config
  855. /// for WebKit. So it is possible that it stops working in a future version.
  856. ///
  857. /// On Android, it sets the `WebSettings.setAllowUniversalAccessFromFileURLs` and any later-created web views uses
  858. /// that value.
  859. /// </summary>
  860. /// <param name="flag">A flag indicates whether the universal access for files are allowed or not.</param>
  861. public static void SetAllowUniversalAccessFromFileURLs(bool flag) {
  862. UniWebViewInterface.SetAllowUniversalAccessFromFileURLs(flag);
  863. }
  864. /// <summary>
  865. /// Sets whether the web view area should avoid soft keyboard. If `true`, when the keyboard shows up, the web views
  866. /// content view will resize itself to avoid keyboard overlap the web content. Otherwise, the web view will not resize
  867. /// and just leave the content below under the soft keyboard.
  868. ///
  869. /// This method is only for Android. On iOS, the keyboard avoidance is built into the system directly and there is
  870. /// no way to change its behavior.
  871. ///
  872. /// Default is `true`.
  873. /// </summary>
  874. /// <param name="flag">Whether the keyboard should avoid web view content.</param>
  875. public static void SetEnableKeyboardAvoidance(bool flag) {
  876. #if UNITY_ANDROID && !UNITY_EDITOR
  877. UniWebViewInterface.SetEnableKeyboardAvoidance(flag);
  878. #endif
  879. }
  880. /// <summary>
  881. /// Sets whether JavaScript should be enabled in current web view. Default is enabled.
  882. /// </summary>
  883. /// <param name="enabled">Whether JavaScript should be enabled.</param>
  884. public static void SetJavaScriptEnabled(bool enabled) {
  885. UniWebViewInterface.SetJavaScriptEnabled(enabled);
  886. }
  887. /// <summary>
  888. /// Sets whether the web view limits navigation to pages within the app’s domain.
  889. ///
  890. /// This only works on iOS 14.0+. For more information, refer to the Apple's documentation:
  891. /// https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/3585117-limitsnavigationstoappbounddomai
  892. /// and the App-Bound Domains page: https://webkit.org/blog/10882/app-bound-domains/
  893. ///
  894. /// This requires additional setup in `WKAppBoundDomains` key in the Info.plist file.
  895. ///
  896. /// On Android, this method does nothing.
  897. /// </summary>
  898. /// <param name="enabled"></param>
  899. public static void SetLimitsNavigationsToAppBoundDomains(bool enabled) {
  900. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  901. UniWebViewInterface.SetLimitsNavigationsToAppBoundDomains(enabled);
  902. #endif
  903. }
  904. /// <summary>
  905. /// Sets whether JavaScript can open windows without user interaction.
  906. ///
  907. /// By setting this to `true`, an automatically JavaScript navigation will be allowed in the web view.
  908. /// </summary>
  909. /// <param name="flag">Whether JavaScript could open window automatically.</param>
  910. public static void SetAllowJavaScriptOpenWindow(bool flag) {
  911. UniWebViewInterface.SetAllowJavaScriptOpenWindow(flag);
  912. }
  913. /// <summary>
  914. /// Sets whether the web page console output should be forwarded to native console.
  915. ///
  916. /// By setting this to `true`, UniWebView will try to intercept the web page console output methods and forward
  917. /// them to the native console, for example, Xcode console on iOS, Android logcat on Android and Unity Console when
  918. /// using Unity Editor on macOS. It provides a way to debug the web page by using the native console without opening
  919. /// the web inspector. The forwarded logs in native side contains a "&lt;UniWebView-Web&gt;" tag.
  920. ///
  921. /// Default is `false`. You need to set it before you create a web view instance to apply this setting. Any existing
  922. /// web views are not affected.
  923. ///
  924. /// Logs from the methods below will be forwarded:
  925. ///
  926. /// - console.log
  927. /// - console.warn
  928. /// - console.error
  929. /// - console.debug
  930. ///
  931. /// </summary>
  932. /// <param name="flag">Whether the web page console output should be forwarded to native output.</param>
  933. public static void SetForwardWebConsoleToNativeOutput(bool flag) {
  934. UniWebViewInterface.SetForwardWebConsoleToNativeOutput(flag);
  935. }
  936. /// <summary>
  937. /// Cleans web view cache. This removes cached local data of web view.
  938. ///
  939. /// If you need to clear all cookies, use `ClearCookies` instead.
  940. /// </summary>
  941. public void CleanCache() {
  942. UniWebViewInterface.CleanCache(listener.Name);
  943. }
  944. /// <summary>
  945. /// Sets the way of how the cache is used when loading a request.
  946. ///
  947. /// The default value is `UniWebViewCacheMode.Default`.
  948. /// </summary>
  949. /// <param name="cacheMode">The desired cache mode which the following request loading should be used.</param>
  950. public void SetCacheMode(UniWebViewCacheMode cacheMode) {
  951. UniWebViewInterface.SetCacheMode(listener.Name, (int)cacheMode);
  952. }
  953. /// <summary>
  954. /// Clears all cookies from web view.
  955. ///
  956. /// This will clear cookies from all domains in the web view and previous.
  957. /// If you only need to remove cookies from a certain domain, use `SetCookie` instead.
  958. /// </summary>
  959. public static void ClearCookies() {
  960. UniWebViewInterface.ClearCookies();
  961. }
  962. /// <summary>
  963. /// Sets a cookie for a certain url.
  964. /// </summary>
  965. /// <param name="url">The url to which cookie will be set.</param>
  966. /// <param name="cookie">The cookie string to set.</param>
  967. /// <param name="skipEncoding">
  968. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  969. /// using it. Otherwise, your original url string will be used to set the cookie if it is valid. Default is `false`.
  970. /// </param>
  971. public static void SetCookie(string url, string cookie, bool skipEncoding = false) {
  972. UniWebViewInterface.SetCookie(url, cookie, skipEncoding);
  973. }
  974. /// <summary>
  975. /// Gets the cookie value under a url and key.
  976. /// </summary>
  977. /// <param name="url">The url (domain) where the target cookie is.</param>
  978. /// <param name="key">The key for target cookie value.</param>
  979. /// <param name="skipEncoding">
  980. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  981. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  982. /// </param>
  983. /// <returns>Value of the target cookie under url.</returns>
  984. public static string GetCookie(string url, string key, bool skipEncoding = false) {
  985. return UniWebViewInterface.GetCookie(url, key, skipEncoding);
  986. }
  987. /// <summary>
  988. /// Removes all the cookies under a url.
  989. /// </summary>
  990. /// <param name="url">The url (domain) where the cookies is under.</param>
  991. /// <param name="skipEncoding">
  992. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  993. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  994. /// </param>
  995. public static void RemoveCookies(string url, bool skipEncoding = false) {
  996. UniWebViewInterface.RemoveCookies(url, skipEncoding);
  997. }
  998. /// <summary>
  999. /// Removes the certain cookie under a url for the specified key.
  1000. /// </summary>
  1001. /// <param name="url">The url (domain) where the cookies is under.</param>
  1002. /// <param name="key">The key for target cookie.</param>
  1003. /// <param name="skipEncoding">
  1004. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  1005. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  1006. /// </param>
  1007. public static void RemoveCooke(string url, string key, bool skipEncoding = false) {
  1008. UniWebViewInterface.RemoveCookie(url, key, skipEncoding);
  1009. }
  1010. /// <summary>
  1011. /// Clears any saved credentials for HTTP authentication for both Basic and Digest.
  1012. ///
  1013. /// On both iOS and Android, the user input credentials will be stored permanently across session.
  1014. /// It could prevent your users to input username and password again until they changed. If you need the
  1015. /// credentials only living in a shorter lifetime, call this method at proper timing.
  1016. ///
  1017. /// On iOS, it will clear the credentials immediately and completely from both disk and network cache.
  1018. /// On Android, it only clears from disk database, the authentication might be still cached in the network stack
  1019. /// and will not be removed until next session (app restarting).
  1020. ///
  1021. /// The client logout mechanism should be implemented by the Web site designer (such as server sending a HTTP
  1022. /// 401 for invalidating credentials).
  1023. ///
  1024. /// </summary>
  1025. /// <param name="host">The host to which the credentials apply. It should not contain any thing like scheme or path part.</param>
  1026. /// <param name="realm">The realm to which the credentials apply.</param>
  1027. public static void ClearHttpAuthUsernamePassword(string host, string realm) {
  1028. UniWebViewInterface.ClearHttpAuthUsernamePassword(host, realm);
  1029. }
  1030. private Color backgroundColor = Color.white;
  1031. /// <summary>
  1032. /// Gets or sets the background color of web view. The default value is `Color.white`.
  1033. /// </summary>
  1034. public Color BackgroundColor {
  1035. get => backgroundColor;
  1036. set {
  1037. backgroundColor = value;
  1038. UniWebViewInterface.SetBackgroundColor(listener.Name, value.r, value.g, value.b, value.a);
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// Gets or sets the alpha value of the whole web view.
  1043. ///
  1044. /// You can make the game scene behind web view visible to make the web view transparent.
  1045. ///
  1046. /// Default is `1.0f`, which means totally opaque. Set it to `0.0f` will make the web view totally transparent.
  1047. /// </summary>
  1048. public float Alpha {
  1049. get => UniWebViewInterface.GetWebViewAlpha(listener.Name);
  1050. set => UniWebViewInterface.SetWebViewAlpha(listener.Name, value);
  1051. }
  1052. /// <summary>
  1053. /// Sets whether to show a loading indicator while the loading is in progress.
  1054. /// </summary>
  1055. /// <param name="flag">Whether an indicator should show.</param>
  1056. public void SetShowSpinnerWhileLoading(bool flag) {
  1057. UniWebViewInterface.SetShowSpinnerWhileLoading(listener.Name, flag);
  1058. }
  1059. /// <summary>
  1060. /// Sets the text displayed in the loading indicator, if `SetShowSpinnerWhileLoading` is set to `true`.
  1061. /// </summary>
  1062. /// <param name="text">The text to display while loading indicator visible. Default is "Loading..."</param>
  1063. public void SetSpinnerText(string text) {
  1064. UniWebViewInterface.SetSpinnerText(listener.Name, text);
  1065. }
  1066. /// <summary>
  1067. /// Sets whether the user can dismiss the loading indicator by tapping on it or the greyed-out background around.
  1068. ///
  1069. /// By default, when the loading spinner is shown, the user can dismiss it by a single tapping. Call this method
  1070. /// with `false` to disable this behavior.
  1071. /// </summary>
  1072. /// <param name="flag">Whether the user can dismiss the loading indicator.</param>
  1073. public void SetAllowUserDismissSpinner(bool flag) {
  1074. UniWebViewInterface.SetAllowUserDismissSpinnerByGesture(listener.Name, flag);
  1075. }
  1076. /// <summary>
  1077. /// Shows the loading spinner.
  1078. ///
  1079. /// Calling this method will show the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  1080. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `true`, UniWebView will still hide
  1081. /// the spinner when the loading finishes.
  1082. /// </summary>
  1083. public void ShowSpinner() {
  1084. UniWebViewInterface.ShowSpinner(listener.Name);
  1085. }
  1086. /// <summary>
  1087. /// Hides the loading spinner.
  1088. ///
  1089. /// Calling this method will hide the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  1090. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `false`, UniWebView will still show
  1091. /// the spinner when the loading starts.
  1092. /// </summary>
  1093. public void HideSpinner() {
  1094. UniWebViewInterface.HideSpinner(listener.Name);
  1095. }
  1096. /// <summary>
  1097. /// Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds.
  1098. ///
  1099. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1100. /// </summary>
  1101. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  1102. public void SetHorizontalScrollBarEnabled(bool enabled) {
  1103. UniWebViewInterface.SetHorizontalScrollBarEnabled(listener.Name, enabled);
  1104. }
  1105. /// <summary>
  1106. /// Sets whether the vertical scroll bar should show when the web content beyonds web view bounds.
  1107. ///
  1108. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1109. /// </summary>
  1110. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  1111. public void SetVerticalScrollBarEnabled(bool enabled) {
  1112. UniWebViewInterface.SetVerticalScrollBarEnabled(listener.Name, enabled);
  1113. }
  1114. /// <summary>
  1115. /// Sets whether the web view should show with a bounces effect when scrolling to page edge.
  1116. ///
  1117. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1118. /// </summary>
  1119. /// <param name="enabled">Whether the bounces effect should be applied or not.</param>
  1120. public void SetBouncesEnabled(bool enabled) {
  1121. UniWebViewInterface.SetBouncesEnabled(listener.Name, enabled);
  1122. }
  1123. /// <summary>
  1124. /// Sets whether the web view supports zoom gesture to change content size.
  1125. /// Default is `false`, which means the zoom gesture is not supported.
  1126. /// </summary>
  1127. /// <param name="enabled">Whether the zoom gesture is allowed or not.</param>
  1128. public void SetZoomEnabled(bool enabled) {
  1129. UniWebViewInterface.SetZoomEnabled(listener.Name, enabled);
  1130. }
  1131. /// <summary>
  1132. /// Adds a trusted domain to white list and allow permission requests from the domain.
  1133. ///
  1134. /// You need this on Android devices when a site needs the location or camera permission. It will allow the
  1135. /// permission gets approved so you could access the corresponding devices.
  1136. ///
  1137. /// Deprecated. Use `RegisterOnRequestMediaCapturePermission` instead, which works for both Android and iOS and
  1138. /// provides a more flexible way to handle the permission requests. By default, if neither this method and
  1139. /// `RegisterOnRequestMediaCapturePermission` is called, the permission request will trigger a grant alert to ask
  1140. /// the user to decide whether to allow or deny the permission.
  1141. ///
  1142. /// </summary>
  1143. /// <param name="domain">The domain to add to the white list.</param>
  1144. [Obsolete("Deprecated. Use `RegisterOnRequestMediaCapturePermission` instead. Check " +
  1145. "https://docs.uniwebview.com/api/#registeronrequestmediacapturepermission", false)]
  1146. public void AddPermissionTrustDomain(string domain) {
  1147. #if UNITY_ANDROID && !UNITY_EDITOR
  1148. UniWebViewInterface.AddPermissionTrustDomain(listener.Name, domain);
  1149. #endif
  1150. }
  1151. /// <summary>
  1152. /// Removes a trusted domain from white list.
  1153. /// </summary>
  1154. /// <param name="domain">The domain to remove from white list.</param>
  1155. [Obsolete("Deprecated. Use `UnregisterOnRequestMediaCapturePermission` instead.", false)]
  1156. public void RemovePermissionTrustDomain(string domain) {
  1157. #if UNITY_ANDROID && !UNITY_EDITOR
  1158. UniWebViewInterface.RemovePermissionTrustDomain(listener.Name, domain);
  1159. #endif
  1160. }
  1161. /// <summary>
  1162. /// Sets whether the device back button should be enabled to execute "go back" or "closing" operation.
  1163. ///
  1164. /// On Android, the device back button in navigation bar will navigate users to a back page. If there is
  1165. /// no any back page avaliable, the back button clicking will try to raise a `OnShouldClose` event and try
  1166. /// to close the web view if `true` is return from the event. If the `OnShouldClose` is not listened,
  1167. /// the web view will be closed and the UniWebView component will be destroyed to release using resource.
  1168. ///
  1169. /// Listen to `OnKeyCodeReceived` if you need to disable the back button, but still want to get the back
  1170. /// button key pressing event.
  1171. ///
  1172. /// Default is enabled.
  1173. /// </summary>
  1174. /// <param name="enabled">Whether the back button should perform go back or closing operation to web view.</param>
  1175. public void SetBackButtonEnabled(bool enabled) {
  1176. this.backButtonEnabled = enabled;
  1177. }
  1178. /// <summary>
  1179. /// Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport.
  1180. /// </summary>
  1181. /// <param name="flag">Whether to enable support for the viewport meta tag.</param>
  1182. public void SetUseWideViewPort(bool flag) {
  1183. #if UNITY_ANDROID && !UNITY_EDITOR
  1184. UniWebViewInterface.SetUseWideViewPort(listener.Name, flag);
  1185. #endif
  1186. }
  1187. /// <summary>
  1188. /// Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width.
  1189. ///
  1190. /// This method is only for Android. Default is disabled.
  1191. /// </summary>
  1192. /// <param name="flag"></param>
  1193. public void SetLoadWithOverviewMode(bool flag) {
  1194. #if UNITY_ANDROID && !UNITY_EDITOR
  1195. UniWebViewInterface.SetLoadWithOverviewMode(listener.Name, flag);
  1196. #endif
  1197. }
  1198. /// <summary>
  1199. /// Sets whether to show a toolbar which contains navigation buttons and Done button.
  1200. ///
  1201. /// You could choose to show or hide the tool bar. By configuring the `animated` and `onTop`
  1202. /// parameters, you can control the animating and position of the toolbar. If the toolbar is
  1203. /// overlapping with some part of your web view, pass `adjustInset` with `true` to have the
  1204. /// web view relocating itself to avoid the overlap.
  1205. ///
  1206. /// This method is only for iOS. The toolbar is hidden by default.
  1207. /// </summary>
  1208. /// <param name="show">Whether the toolbar should show or hide.</param>
  1209. /// <param name="animated">Whether the toolbar state changing should be with animation. Default is `false`.</param>
  1210. /// <param name="onTop">Whether the toolbar should snap to top of screen or to bottom of screen.
  1211. /// Default is `true`</param>
  1212. /// <param name="adjustInset">Whether the toolbar transition should also adjust web view position and size
  1213. /// if overlapped. Default is `false`</param>
  1214. [Obsolete("`SetShowToolbar` is deprecated. Use `EmbeddedToolbar.Show()` or `EmbeddedToolbar.Hide()`" +
  1215. "instead.", false)]
  1216. public void SetShowToolbar(bool show, bool animated = false, bool onTop = true, bool adjustInset = false) {
  1217. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1218. UniWebViewInterface.SetShowToolbar(listener.Name, show, animated, onTop, adjustInset);
  1219. #endif
  1220. }
  1221. /// <summary>
  1222. /// Sets the done button text in toolbar.
  1223. ///
  1224. /// By default, UniWebView will show a "Done" button at right size in the
  1225. /// toolbar. You could change its title by passing a text.
  1226. ///
  1227. /// This method is only for iOS, since there is no toolbar on Android.
  1228. /// </summary>
  1229. /// <param name="text">The text needed to be set as done button title.</param>
  1230. [Obsolete("`SetToolbarDoneButtonText` is deprecated. Use `EmbeddedToolbar.SetDoneButtonText` " +
  1231. "instead.", false)]
  1232. public void SetToolbarDoneButtonText(string text) {
  1233. #if UNITY_IOS && !UNITY_EDITOR
  1234. UniWebViewInterface.SetToolbarDoneButtonText(listener.Name, text);
  1235. #endif
  1236. }
  1237. /// <summary>
  1238. /// Sets the go back button text in toolbar.
  1239. ///
  1240. /// By default, UniWebView will show a back arrow at the left side in the
  1241. /// toolbar. You could change its text.
  1242. ///
  1243. /// This method is only for iOS and macOS Editor, since there is no toolbar on Android.
  1244. /// </summary>
  1245. /// <param name="text">The text needed to be set as go back button.</param>
  1246. [Obsolete("`SetToolbarGoBackButtonText` is deprecated. Use `EmbeddedToolbar.SetGoBackButtonText` " +
  1247. "instead.", false)]
  1248. public void SetToolbarGoBackButtonText(string text) {
  1249. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1250. UniWebViewInterface.SetToolbarGoBackButtonText(listener.Name, text);
  1251. #endif
  1252. }
  1253. /// <summary>
  1254. /// Sets the go forward button text in toolbar.
  1255. ///
  1256. /// By default, UniWebView will show a forward arrow at the left side in the
  1257. /// toolbar. You could change its text.
  1258. ///
  1259. /// This method is only for iOS and macOS Editor, since there is no toolbar on Android.
  1260. /// </summary>
  1261. /// <param name="text">The text needed to be set as go forward button.</param>
  1262. [Obsolete("`SetToolbarGoForwardButtonText` is deprecated. Use `EmbeddedToolbar.SetGoForwardButtonText` " +
  1263. "instead.", false)]
  1264. public void SetToolbarGoForwardButtonText(string text) {
  1265. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1266. UniWebViewInterface.SetToolbarGoForwardButtonText(listener.Name, text);
  1267. #endif
  1268. }
  1269. /// <summary>
  1270. /// Sets the background tint color for the toolbar.
  1271. ///
  1272. /// By default, UniWebView uses a default half-transparent iOS standard background for toolbar.
  1273. /// You can change it by setting a new opaque color.
  1274. ///
  1275. /// This method is only for iOS, since there is no toolbar on Android.
  1276. /// </summary>
  1277. /// <param name="color">The color should be used for the background tint of the toolbar.</param>
  1278. [Obsolete("`SetToolbarTintColor` is deprecated. Use `EmbeddedToolbar.SetBackgroundColor` " +
  1279. "instead.", false)]
  1280. public void SetToolbarTintColor(Color color) {
  1281. #if UNITY_IOS && !UNITY_EDITOR
  1282. UniWebViewInterface.SetToolbarTintColor(listener.Name, color.r, color.g, color.b);
  1283. #endif
  1284. }
  1285. /// <summary>
  1286. /// Sets the button text color for the toolbar.
  1287. ///
  1288. /// By default, UniWebView uses the default text color on iOS, which is blue for most cases.
  1289. /// You can change it by setting a new opaque color.
  1290. ///
  1291. /// This method is only for iOS, since there is no toolbar on Android.
  1292. /// </summary>
  1293. /// <param name="color">The color should be used for the button text of the toolbar.</param>
  1294. [Obsolete("`SetToolbarTextColor` is deprecated. Use `EmbeddedToolbar.SetButtonTextColor` or " +
  1295. "`EmbeddedToolbar.SetTitleTextColor` instead.", false)]
  1296. public void SetToolbarTextColor(Color color) {
  1297. #if UNITY_IOS && !UNITY_EDITOR
  1298. UniWebViewInterface.SetToolbarTextColor(listener.Name, color.r, color.g, color.b);
  1299. #endif
  1300. }
  1301. /// <summary>
  1302. /// Sets the visibility of navigation buttons, such as "Go Back" and "Go Forward", on toolbar.
  1303. ///
  1304. /// By default, UniWebView will show the "Go Back" and "Go Forward" navigation buttons on the toolbar.
  1305. /// Users can use these buttons to perform go back or go forward action just like in a browser. If the navigation
  1306. /// model is not for your case, call this method with `false` as `show` parameter to hide them.
  1307. ///
  1308. /// This method is only for iOS, since there is no toolbar on Android.
  1309. /// </summary>
  1310. /// <param name="show">Whether the navigation buttons on the toolbar should show or hide.</param>
  1311. [Obsolete("`SetShowToolbarNavigationButtons` is deprecated. Use `EmbeddedToolbar.ShowNavigationButtons` or " +
  1312. "`EmbeddedToolbar.HideNavigationButtons` instead.", false)]
  1313. public void SetShowToolbarNavigationButtons(bool show) {
  1314. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1315. UniWebViewInterface.SetShowToolbarNavigationButtons(listener.Name, show);
  1316. #endif
  1317. }
  1318. /// <summary>
  1319. /// Sets whether the web view can receive user interaction or not.
  1320. ///
  1321. /// By setting this to `false`, the web view will not accept any user touch event so your users cannot tap links or
  1322. /// scroll the page.
  1323. ///
  1324. /// </summary>
  1325. /// <param name="enabled">Whether the user interaction should be enabled or not.</param>
  1326. public void SetUserInteractionEnabled(bool enabled) {
  1327. UniWebViewInterface.SetUserInteractionEnabled(listener.Name, enabled);
  1328. }
  1329. /// <summary>
  1330. /// Sets whether the web view should pass through clicks at clear pixels to Unity scene.
  1331. ///
  1332. /// Setting this method is a pre-condition for the whole passing-through feature to work. To allow your touch passing through
  1333. /// to Unity scene, the following conditions should be met at the same time:
  1334. ///
  1335. /// 1. This method is called with `true` and the web view accepts passing-through clicks.
  1336. /// 2. The web view has a transparent background in body style for its content by CSS.
  1337. /// 3. The web view itself has a transparent background color by setting `BackgroundColor` with a clear color.
  1338. ///
  1339. /// Then, when user clicks on the clear pixel on the web view, the touch events will not be handled by the web view.
  1340. /// Instead, these events are passed to Unity scene. By using this feature, it is possible to create a native UI with the
  1341. /// web view.
  1342. ///
  1343. /// Only clicks on transparent part on the web view will be delivered to Unity scene. The web view still intercepts
  1344. /// and handles other touches on visible pixels on the web view.
  1345. /// </summary>
  1346. /// <param name="enabled">Whether the transparency clicking through feature should be enabled in this web view.</param>
  1347. public void SetTransparencyClickingThroughEnabled(bool enabled) {
  1348. UniWebViewInterface.SetTransparencyClickingThroughEnabled(listener.Name, enabled);
  1349. }
  1350. /// <summary>
  1351. /// Enables debugging of web contents. You could inspect of the content of a
  1352. /// web view by using a browser development tool of Chrome for Android or Safari for macOS.
  1353. ///
  1354. /// This method is only for Android and macOS Editor. On iOS, you do not need additional step.
  1355. /// You could open Safari's developer tools to debug a web view on iOS.
  1356. /// </summary>
  1357. /// <param name="enabled">Whether the content debugging should be enabled.</param>
  1358. public static void SetWebContentsDebuggingEnabled(bool enabled) {
  1359. UniWebViewInterface.SetWebContentsDebuggingEnabled(enabled);
  1360. }
  1361. /// <summary>
  1362. /// Enables user resizing for web view window. By default, you can only set the window size
  1363. /// by setting its frame on mac Editor. By enabling user resizing, you would be able to resize
  1364. /// the window by dragging its border as a normal macOS window.
  1365. ///
  1366. /// This method only works for macOS for debugging purpose. It does nothing on iOS and Android.
  1367. /// </summary>
  1368. /// <param name="enabled">Whether the window could be able to be resized by cursor.</param>
  1369. public void SetWindowUserResizeEnabled(bool enabled) {
  1370. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1371. UniWebViewInterface.SetWindowUserResizeEnabled(listener.Name, enabled);
  1372. #endif
  1373. }
  1374. /// <summary>
  1375. /// Gets the HTML content from current page by accessing its outerHTML with JavaScript.
  1376. /// </summary>
  1377. /// <param name="handler">Called after the JavaScript executed. The parameter string is the content read
  1378. /// from page.</param>
  1379. public void GetHTMLContent(Action<string> handler) {
  1380. EvaluateJavaScript("document.documentElement.outerHTML", payload => {
  1381. if (handler != null) {
  1382. handler(payload.data);
  1383. }
  1384. });
  1385. }
  1386. /// <summary>
  1387. /// Sets whether horizontal swipe gestures should trigger back-forward list navigation.
  1388. ///
  1389. /// By setting with `true`, users can swipe from screen edge to perform a back or forward navigation.
  1390. /// This method only works on iOS and macOS Editor. Default is `false`.
  1391. ///
  1392. /// On Android, the screen navigation gestures are simulating the traditional back button and it is enabled by
  1393. /// default. To disable gesture navigation on Android, you have to also disable the device back button. See
  1394. /// `SetBackButtonEnabled` for that purpose.
  1395. /// </summary>
  1396. /// <param name="flag">
  1397. /// The value indicates whether a swipe gestures driven navigation should be allowed. Default is `false`.
  1398. /// </param>
  1399. public void SetAllowBackForwardNavigationGestures(bool flag) {
  1400. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1401. UniWebViewInterface.SetAllowBackForwardNavigationGestures(listener.Name, flag);
  1402. #endif
  1403. }
  1404. /// <summary>
  1405. /// Sets whether a prompt alert should be displayed for collection username and password when the web view receives an
  1406. /// HTTP authentication challenge (HTTP Basic or HTTP Digest) from server.
  1407. ///
  1408. /// By setting with `false`, no prompt will be shown and the user cannot login with input credentials. In this case,
  1409. /// you can only access this page by providing username and password through the URL like: "http://username:password@example.com".
  1410. /// If the username and password does not match, normally an error with 401 as status code would be returned (this behavior depends
  1411. /// on the server implementation). If set with `true`, a prompt will be shown when there is no credentials provided or it is not
  1412. /// correct in the URL.
  1413. ///
  1414. /// Default is `true`.
  1415. /// </summary>
  1416. /// <param name="flag">Whether a prompt alert should be shown for HTTP authentication challenge or not.</param>
  1417. public void SetAllowHTTPAuthPopUpWindow(bool flag) {
  1418. UniWebViewInterface.SetAllowHTTPAuthPopUpWindow(listener.Name, flag);
  1419. }
  1420. /// <summary>
  1421. /// Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content.
  1422. ///
  1423. /// When enabled, when user long presses an image or link in the web page, a context menu would be show up to ask
  1424. /// user's action. On iOS, it is a action sheet to ask whether opening the target link or saving the image. On
  1425. /// Android it is a pop up dialog to ask whether saving the image to local disk. On iOS, the preview page triggered
  1426. /// by force touch on iOS is also considered as a callout menu.
  1427. ///
  1428. /// Default is `true`, means that the callout menu will be displayed. Call this method with `false` to disable
  1429. /// it on the web view.
  1430. /// </summary>
  1431. /// <param name="enabled">
  1432. /// Whether a callout menu should be displayed when user long pressing or force touching a certain web page element.
  1433. /// </param>
  1434. public void SetCalloutEnabled(bool enabled) {
  1435. UniWebViewInterface.SetCalloutEnabled(listener.Name, enabled);
  1436. }
  1437. [ObsoleteAttribute("Deprecated. Use `SetSupportMultipleWindows(bool enabled, bool allowJavaScriptOpen)` to set `allowJavaScriptOpen` explicitly.")]
  1438. public void SetSupportMultipleWindows(bool enabled) {
  1439. SetSupportMultipleWindows(enabled, true);
  1440. }
  1441. /// <summary>
  1442. /// Sets whether the web view should support a pop up web view triggered by user in a new tab.
  1443. ///
  1444. /// In a general web browser (such as Google Chrome or Safari), a URL with `target="_blank"` attribute is intended
  1445. /// to be opened in a new tab. However, in the context of web view, there is no way to handle new tabs without
  1446. /// proper configurations. Due to that, by default UniWebView will ignore the `target="_blank"` and try to open
  1447. /// the page in the same web view if that kind of link is pressed.
  1448. ///
  1449. /// It works for most cases, but if this is a problem to your app logic, you can change this behavior by calling
  1450. /// this method with `enabled` set to `true`. It enables the "opening in new tab" behavior in a limited way, by
  1451. /// adding the new tab web view above to the current web view, with the same size and position. When the opened new
  1452. /// tab is closed, it will be removed from the view hierarchy automatically.
  1453. ///
  1454. /// By default, only user triggered action is allowed to open a new window for security reason. That means, if you
  1455. /// are using some JavaScript like `window.open`, unless you set `allowJavaScriptOpening` to `true`, it won't work.
  1456. /// This default behavior prevents any other third party JavaScript code from opening a window arbitrarily.
  1457. ///
  1458. /// </summary>
  1459. /// <param name="enabled">
  1460. /// Whether to support multiple windows. If `true`, the `target="_blank"` link will be opened in a new web view.
  1461. /// Default is `false`.
  1462. /// </param>
  1463. /// <param name="allowJavaScriptOpening">
  1464. /// Whether to support open the new window with JavaScript by `window.open`. Setting this to `true` means any JavaScript
  1465. /// code, even from third party (in an iframe or a library on the page), can open a new window. Use it as your risk.
  1466. /// </param>
  1467. public void SetSupportMultipleWindows(bool enabled, bool allowJavaScriptOpening) {
  1468. UniWebViewInterface.SetSupportMultipleWindows(listener.Name, enabled, allowJavaScriptOpening);
  1469. }
  1470. /// <summary>
  1471. /// Sets the default font size used in the web view.
  1472. ///
  1473. /// On Android, the web view font size can be affected by the system font scale setting. Use this method to set the
  1474. /// font size in a more reasonable way, by giving the web view another default font size with the system font scale
  1475. /// considered. It can removes or reduces the effect of system font scale when displaying the web content.
  1476. ///
  1477. /// This method only works on Android. On iOS, this method does nothing since the web view will respect the font
  1478. /// size setting in your CSS styles.
  1479. /// </summary>
  1480. /// <param name="size">The target default font size set to the web view.</param>
  1481. public void SetDefaultFontSize(int size) {
  1482. #if UNITY_ANDROID && !UNITY_EDITOR
  1483. UniWebViewInterface.SetDefaultFontSize(listener.Name, size);
  1484. #endif
  1485. }
  1486. /// <summary>
  1487. /// Sets the text zoom used in the web view.
  1488. ///
  1489. /// On Android, this method call `WebSettings.setTextZoom` to the the text zoom used in the web view.
  1490. ///
  1491. /// This method only works on Android.
  1492. /// </summary>
  1493. /// <param name="textZoom">The text zoom in percent.</param>
  1494. public void SetTextZoom(int textZoom) {
  1495. #if UNITY_ANDROID && !UNITY_EDITOR
  1496. UniWebViewInterface.SetTextZoom(listener.Name, textZoom);
  1497. #endif
  1498. }
  1499. /// <summary>
  1500. /// Sets whether the drag interaction should be enabled on iOS.
  1501. ///
  1502. /// From iOS 11, the web view on iOS supports the drag interaction when user long presses an image, link or text.
  1503. /// Setting this to `false` would disable the drag feather on the web view.
  1504. ///
  1505. /// On Android, there is no direct native way to disable drag only. This method instead disables the long touch
  1506. /// event, which is used as a trigger for drag interaction. So, setting this to `false` would disable the long
  1507. /// touch gesture as a side effect.
  1508. ///
  1509. /// It does nothing on macOS editor. Default is `true`, which means drag interaction is enabled if the device and
  1510. /// system version supports it.
  1511. /// </summary>
  1512. /// <param name="enabled">
  1513. /// Whether the drag interaction should be enabled.
  1514. /// </param>
  1515. public void SetDragInteractionEnabled(bool enabled) {
  1516. UniWebViewInterface.SetDragInteractionEnabled(listener.Name, enabled);
  1517. }
  1518. /// <summary>
  1519. /// Prints current page.
  1520. ///
  1521. /// By calling this method, a native print preview panel will be brought up on iOS and Android.
  1522. /// This method does nothing on macOS editor.
  1523. /// On iOS and Android, the web view does not support JavaScript (window.print()),
  1524. /// you can only initialize a print job from Unity by this method.
  1525. /// </summary>
  1526. public void Print() {
  1527. UniWebViewInterface.Print(listener.Name);
  1528. }
  1529. /// <summary>
  1530. /// Capture the content of web view and store it to the cache path on disk with the given file name.
  1531. ///
  1532. /// When the capturing finishes, `OnCaptureSnapshotFinished` event will be raised, with an error code to indicate
  1533. /// whether the operation succeeded and an accessible disk path of the image.
  1534. ///
  1535. /// The captured image will be stored as a PNG file under the `fileName` in app's cache folder. If a file with the
  1536. /// same file name already exists, it will be overridden by the new captured image.
  1537. /// </summary>
  1538. /// <param name="fileName">
  1539. /// The file name to which the captured image is stored to, for example "screenshot.png". If empty, UniWebView will
  1540. /// pick a random UUID with "png" file extension as the file name.
  1541. /// </param>
  1542. public void CaptureSnapshot(string fileName) {
  1543. UniWebViewInterface.CaptureSnapshot(listener.Name, fileName);
  1544. }
  1545. /// <summary>
  1546. /// Scrolls the web view to a certain point.
  1547. ///
  1548. /// Use 0 for both `x` and `y` value to scroll the web view to its origin.
  1549. /// In a normal vertical web page, it is equivalent as scrolling to top.
  1550. ///
  1551. /// You can use the `animated` parameter to control whether scrolling the page with or without animation.
  1552. /// This parameter only works on iOS and Android. On macOS editor, the scrolling always happens without animation.
  1553. /// </summary>
  1554. /// <param name="x">X value of the target scrolling point.</param>
  1555. /// <param name="y">Y value of the target scrolling point.</param>
  1556. /// <param name="animated">If `true`, the scrolling happens with animation. Otherwise, it happens without
  1557. /// animation and the content is set directly.
  1558. /// </param>
  1559. public void ScrollTo(int x, int y, bool animated) {
  1560. UniWebViewInterface.ScrollTo(listener.Name, x, y, animated);
  1561. }
  1562. /// <summary>
  1563. /// Adds the URL to download inspecting list.
  1564. ///
  1565. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  1566. /// triggered. Check "Download Files" guide for more.
  1567. ///
  1568. /// This method only works on iOS and macOS Editor.
  1569. /// </summary>
  1570. /// <param name="urlString">The inspected URL.</param>
  1571. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  1572. public void AddDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1573. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1574. UniWebViewInterface.AddDownloadURL(listener.Name, urlString, (int)type);
  1575. #endif
  1576. }
  1577. /// <summary>
  1578. /// Removes the URL from download inspecting list.
  1579. ///
  1580. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  1581. /// triggered. Check "Download Files" guide for more.
  1582. ///
  1583. /// This method only works on iOS and macOS Editor.
  1584. /// </summary>
  1585. /// <param name="urlString">The inspected URL.</param>
  1586. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  1587. ///
  1588. public void RemoveDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1589. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1590. UniWebViewInterface.RemoveDownloadURL(listener.Name, urlString, (int)type);
  1591. #endif
  1592. }
  1593. /// <summary>
  1594. /// Adds the MIME type to download inspecting list.
  1595. ///
  1596. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  1597. /// download task will be triggered. Check "Download Files" guide for more.
  1598. ///
  1599. /// This method only works on iOS and macOS Editor.
  1600. /// </summary>
  1601. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  1602. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  1603. public void AddDownloadMIMEType(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1604. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1605. UniWebViewInterface.AddDownloadMIMEType(listener.Name, MIMEType, (int)type);
  1606. #endif
  1607. }
  1608. /// <summary>
  1609. /// Removes the MIME type from download inspecting list.
  1610. ///
  1611. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  1612. /// download task will be triggered. Check "Download Files" guide for more.
  1613. ///
  1614. /// This method only works on iOS and macOS Editor.
  1615. /// </summary>
  1616. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  1617. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  1618. public void RemoveDownloadMIMETypes(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1619. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1620. UniWebViewInterface.RemoveDownloadMIMETypes(listener.Name, MIMEType, (int)type);
  1621. #endif
  1622. }
  1623. /// <summary>
  1624. /// Sets whether allowing users to edit the file name before downloading. Default is `true`.
  1625. ///
  1626. /// If `true`, when a download task is triggered, a dialog will be shown to ask user to edit the file name and the
  1627. /// user has a chance to choose if the they actually want to download the file. If `false`, the file download will
  1628. /// start immediately without asking user to edit the file name. The file name is generated by guessing from the
  1629. /// content disposition header and the MIME type. If the guessing of the file name fails, a random string will be
  1630. /// used.
  1631. ///
  1632. /// </summary>
  1633. /// <param name="allowed">
  1634. /// Whether the user can edit the file name and determine whether actually starting the downloading.
  1635. /// </param>
  1636. public void SetAllowUserEditFileNameBeforeDownloading(bool allowed) {
  1637. UniWebViewInterface.SetAllowUserEditFileNameBeforeDownloading(listener.Name, allowed);
  1638. }
  1639. /// <summary>
  1640. /// Sets whether allowing users to choose the way to handle the downloaded file. Default is `true`.
  1641. ///
  1642. /// On iOS, the downloaded file will be stored in a temporary folder. Setting this to `true` will show a system
  1643. /// default share sheet and give the user a chance to send and store the file to another location (such as the
  1644. /// File app or iCloud).
  1645. ///
  1646. /// On macOS Editor, setting this to `true` will allow UniWebView to open the file in Finder.
  1647. ///
  1648. /// This method does not have any effect on Android. On Android, the file is downloaded to the Download folder.
  1649. ///
  1650. /// </summary>
  1651. /// <param name="allowed">Whether the user can choose the way to handle the downloaded file.</param>
  1652. public void SetAllowUserChooseActionAfterDownloading(bool allowed) {
  1653. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1654. UniWebViewInterface.SetAllowUserChooseActionAfterDownloading(listener.Name, allowed);
  1655. #endif
  1656. }
  1657. /// <summary>
  1658. /// Sets whether the `OnFileDownloadStarted` and `OnFileDownloadFinished` events should be raised even for an image
  1659. /// saving action triggered by the callout (context) menu on Android.
  1660. ///
  1661. /// By default, the image saving goes through a different route and it does not trigger the `OnFileDownloadStarted`
  1662. /// and `OnFileDownloadFinished` events like other normal download tasks. Setting this with enabled with `true` if
  1663. /// you also need to get notified when user long-presses on the image and taps "Save Image" button. By default, the
  1664. /// image will be saved to the Downloads directory and you can get the path from the parameter
  1665. /// of `OnFileDownloadFinished` event.
  1666. ///
  1667. /// This only works on Android. On iOS, there is no way to get a callback or any event from the "Add to Photos"
  1668. /// button in the callout menu.
  1669. /// </summary>
  1670. /// <param name="enabled">Whether the context menu image saving action triggers the download related events.</param>
  1671. public void SetDownloadEventForContextMenuEnabled(bool enabled) {
  1672. #if UNITY_ANDROID && !UNITY_EDITOR
  1673. UniWebViewInterface.SetDownloadEventForContextMenuEnabled(listener.Name, enabled);
  1674. #endif
  1675. }
  1676. /// <summary>
  1677. /// Starts the process of continually rendering the snapshot.
  1678. /// </summary>
  1679. /// <remarks>
  1680. /// <para>
  1681. /// You take the responsibility of calling this method before you use either <see cref="GetRenderedData(Rect?)"/> or
  1682. /// <see cref="CreateRenderedTexture(Rect?)"/> to get the rendered data or texture. It prepares a render buffer for the image
  1683. /// data and performs the initial rendering for later use.
  1684. /// </para>
  1685. /// <para>
  1686. /// If this method is not called, the related data or texture methods will not work and will only return <c>null</c>. Once you
  1687. /// no longer need the web view to be rendered as a texture, you should call <see cref="StopSnapshotForRendering"/> to clean up
  1688. /// the associated resources.
  1689. /// </para>
  1690. /// </remarks>
  1691. /// <param name="rect">The optional rectangle to specify the area for rendering. If <c>null</c>, the entire view is rendered.</param>
  1692. /// <param name="onStarted">
  1693. /// An optional callback to execute when rendering has started. The callback receives a <see cref="Texture2D"/> parameter
  1694. /// representing the rendered texture.
  1695. /// </param>
  1696. public void StartSnapshotForRendering(Rect? rect = null, Action<Texture2D> onStarted = null) {
  1697. string identifier = null;
  1698. if (onStarted != null) {
  1699. identifier = Guid.NewGuid().ToString();
  1700. actions.Add(identifier, () => {
  1701. var texture = CreateRenderedTexture(rect);
  1702. onStarted(texture);
  1703. });
  1704. }
  1705. UniWebViewInterface.StartSnapshotForRendering(listener.Name, identifier);
  1706. }
  1707. /// <summary>
  1708. /// Stops the process of continually rendering the snapshot.
  1709. /// </summary>
  1710. /// <remarks>
  1711. /// <para>
  1712. /// You should call this method when you no longer need any further data or texture from the
  1713. /// <see cref="GetRenderedData(Rect?)"/> or <see cref="CreateRenderedTexture(Rect?)"/> methods. This helps in releasing
  1714. /// resources and terminating the rendering process.
  1715. /// </para>
  1716. /// </remarks>
  1717. public void StopSnapshotForRendering() {
  1718. UniWebViewInterface.StopSnapshotForRendering(listener.Name);
  1719. }
  1720. /// <summary>
  1721. /// Gets the data of the rendered image for the current web view.
  1722. /// </summary>
  1723. /// <remarks>
  1724. /// <para>
  1725. /// This method provides you with the raw bytes of the rendered image data in PNG format. To successfully retrieve the
  1726. /// current rendered data, you should first call <see cref="StartSnapshotForRendering"/> to initiate the rendering process.
  1727. /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
  1728. /// </para>
  1729. /// <para>
  1730. /// The rendering area specified by the <paramref name="rect"/> parameter is based on the local coordinates of the web view.
  1731. /// For example, <c>new Rect(webView.frame.width / 2, webView.frame.height / 2, 100, 100)</c> means setting the origin to the
  1732. /// center of the web view and taking a 100x100 square as the snapshot area.
  1733. /// </para>
  1734. /// <para>
  1735. /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos
  1736. /// and WebGL content, will appear as a black rectangle in the rendered image.
  1737. /// </para>
  1738. /// </remarks>
  1739. /// <param name="rect">
  1740. /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used,
  1741. /// the whole web view frame will be used as the snapshot area.
  1742. /// </param>
  1743. /// <returns>
  1744. /// An array of raw bytes representing the rendered image data in PNG format, or <c>null</c> if the rendering process fails
  1745. /// or if the data is not prepared.
  1746. /// </returns>
  1747. /// <seealso cref="StartSnapshotForRendering"/>
  1748. public byte[] GetRenderedData(Rect? rect = null) {
  1749. var r = rect ?? snapshotFullViewRect;
  1750. return UniWebViewInterface.GetRenderedData(
  1751. listener.Name, (int)r.x, (int)r.y, (int)r.width, (int)r.height
  1752. );
  1753. }
  1754. /// <summary>
  1755. /// Creates a rendered texture for the current web view.
  1756. /// </summary>
  1757. /// <remarks>
  1758. /// <para>
  1759. /// You should destroy the returned texture using the `Destroy` method when you no longer need it to free up resources.
  1760. /// </para>
  1761. /// <para>
  1762. /// This method provides you with a texture of the rendered image for the web view, which you can use in your 3D game world.
  1763. /// To obtain the current rendered data, you should call <see cref="StartSnapshotForRendering"/> before using this method.
  1764. /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
  1765. /// </para>
  1766. /// <para>
  1767. /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos
  1768. /// and WebGL content, will appear as a black rectangle in the rendered image.
  1769. /// </para>
  1770. /// <para>
  1771. /// This method returns a plain <see cref="Texture2D"/> object. The texture is not user interactive and can only be used for
  1772. /// display purposes. It is your responsibility to call the `Destroy` method on this texture when you no longer need it.
  1773. /// </para>
  1774. /// </remarks>
  1775. /// <param name="rect">
  1776. /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used,
  1777. /// the whole web view frame will be used as the snapshot area.
  1778. /// </param>
  1779. /// <returns>
  1780. /// A rendered texture of the current web view, or <c>null</c> if the rendering process fails or if the data is not prepared.
  1781. /// </returns>
  1782. /// <seealso cref="StartSnapshotForRendering"/>
  1783. public Texture2D CreateRenderedTexture(Rect? rect = null) {
  1784. var bytes = GetRenderedData(rect);
  1785. if (bytes == null) {
  1786. return null;
  1787. }
  1788. Texture2D texture = new Texture2D(2, 2, TextureFormat.RGB24, false);
  1789. texture.LoadImage(bytes);
  1790. return texture;
  1791. }
  1792. /// <summary>
  1793. /// Registers a method handler for deciding whether UniWebView should handle the request received by the web view.
  1794. ///
  1795. /// The handler is called before the web view actually starts to load the new request. You can check the request
  1796. /// properties, such as the URL, to decide whether UniWebView should continue to handle the request or not. If you
  1797. /// return `true` from the handler function, UniWebView will continue to load the request. Otherwise, UniWebView
  1798. /// will stop the loading.
  1799. /// </summary>
  1800. /// <param name="handler">
  1801. /// A handler you can implement your own logic against the input request value. You need to return a boolean value
  1802. /// to indicate whether UniWebView should continue to load the request or not as soon as possible.
  1803. /// </param>
  1804. public void RegisterShouldHandleRequest(Func<UniWebViewChannelMethodHandleRequest, bool> handler) {
  1805. object Func(object obj) => handler((UniWebViewChannelMethodHandleRequest)obj);
  1806. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  1807. listener.Name,
  1808. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest,
  1809. Func
  1810. );
  1811. }
  1812. /// <summary>
  1813. /// Unregisters the method handler for handling request received by the web view.
  1814. ///
  1815. /// This clears the handler registered by `RegisterHandlingRequest` method.
  1816. /// </summary>
  1817. public void UnregisterShouldHandleRequest() {
  1818. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  1819. listener.Name,
  1820. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest
  1821. );
  1822. }
  1823. /// <summary>
  1824. /// Registers a method handler for deciding whether UniWebView should allow a media request from the web page or
  1825. /// not.
  1826. ///
  1827. /// The handler is called when the web view receives a request to capture media, such as camera or microphone. It
  1828. /// usually happens when the web view is trying to access the camera or microphone by using the "getUserMedia" APIs
  1829. /// in WebRTC. You can check the request properties in the input `UniWebViewChannelMethodMediaCapturePermission`
  1830. /// instance, which contains information like the media type, the request origin (protocol and host), then decide
  1831. /// whether this media request should be allowed or not.
  1832. ///
  1833. /// According to the `UniWebViewMediaCapturePermissionDecision` value you return from the handler function,
  1834. /// UniWebView behaves differently:
  1835. ///
  1836. /// - `Grant`: UniWebView allows the access without asking the user.
  1837. /// - `Deny`: UniWebView forbids the access and the web page will receive an error.
  1838. /// - `Prompt`: UniWebView asks the user for permission. The web page will receive a prompt to ask the user if they
  1839. /// allow the access to the requested media resources (camera or/and microphone).
  1840. ///
  1841. /// If this method is never called or the handler is unregistered, UniWebView will prompt the user for the
  1842. /// permission.
  1843. ///
  1844. /// On iOS, this method is available from iOS 15.0 or later. On earlier version of iOS, the handler will be ignored
  1845. /// and the web view will always prompt the user for the permission.
  1846. ///
  1847. /// </summary>
  1848. /// <param name="handler">
  1849. /// A handler you can implement your own logic to decide whether UniWebView should allow, deny or prompt the media
  1850. /// resource access request.
  1851. ///
  1852. /// You need to return a `UniWebViewMediaCapturePermissionDecision` value to indicate the decision as soon as
  1853. /// possible.
  1854. /// </param>
  1855. public void RegisterOnRequestMediaCapturePermission(
  1856. Func<
  1857. UniWebViewChannelMethodMediaCapturePermission,
  1858. UniWebViewMediaCapturePermissionDecision
  1859. > handler
  1860. )
  1861. {
  1862. object Func(object obj) => handler((UniWebViewChannelMethodMediaCapturePermission)obj);
  1863. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  1864. listener.Name,
  1865. UniWebViewChannelMethod.RequestMediaCapturePermission,
  1866. Func
  1867. );
  1868. }
  1869. /// <summary>
  1870. /// Unregisters the method handler for handling media capture permission request.
  1871. ///
  1872. /// This clears the handler registered by `RegisterOnRequestMediaCapturePermission` method.
  1873. /// </summary>
  1874. public void UnregisterOnRequestMediaCapturePermission() {
  1875. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  1876. listener.Name,
  1877. UniWebViewChannelMethod.RequestMediaCapturePermission
  1878. );
  1879. }
  1880. void OnDestroy() {
  1881. UniWebViewNativeListener.RemoveListener(listener.Name);
  1882. UniWebViewChannelMethodManager.Instance.UnregisterChannel(listener.Name);
  1883. UniWebViewInterface.Destroy(listener.Name);
  1884. Destroy(listener.gameObject);
  1885. }
  1886. #if UNITY_ANDROID && !UNITY_EDITOR
  1887. // From Unity 2022.3.10, the player view is brought to front when switching back from a pause
  1888. // state. Requiring to bring the web view to front to make the web view visible.
  1889. // Issue caused by:
  1890. // 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
  1891. //
  1892. // Ref: UWV-1061
  1893. void OnApplicationPause(bool pauseStatus) {
  1894. if (RestoreViewHierarchyOnResume && !pauseStatus) {
  1895. UniWebViewInterface.BringContentToFront(listener.Name);
  1896. }
  1897. }
  1898. #endif
  1899. /* //////////////////////////////////////////////////////
  1900. // Internal Listener Interface
  1901. ////////////////////////////////////////////////////// */
  1902. internal void InternalOnShowTransitionFinished(string identifier) {
  1903. Action action;
  1904. if (actions.TryGetValue(identifier, out action)) {
  1905. action();
  1906. actions.Remove(identifier);
  1907. }
  1908. }
  1909. internal void InternalOnHideTransitionFinished(string identifier) {
  1910. Action action;
  1911. if (actions.TryGetValue(identifier, out action)) {
  1912. action();
  1913. actions.Remove(identifier);
  1914. }
  1915. }
  1916. internal void InternalOnAnimateToFinished(string identifier) {
  1917. Action action;
  1918. if (actions.TryGetValue(identifier, out action)) {
  1919. action();
  1920. actions.Remove(identifier);
  1921. }
  1922. }
  1923. internal void InternalOnAddJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1924. Action<UniWebViewNativeResultPayload> action;
  1925. var identifier = payload.identifier;
  1926. if (payloadActions.TryGetValue(identifier, out action)) {
  1927. action(payload);
  1928. payloadActions.Remove(identifier);
  1929. }
  1930. }
  1931. internal void InternalOnEvalJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1932. Action<UniWebViewNativeResultPayload> action;
  1933. var identifier = payload.identifier;
  1934. if (payloadActions.TryGetValue(identifier, out action)) {
  1935. action(payload);
  1936. payloadActions.Remove(identifier);
  1937. }
  1938. }
  1939. internal void InternalOnPageFinished(UniWebViewNativeResultPayload payload) {
  1940. if (OnPageFinished != null) {
  1941. int code = -1;
  1942. if (int.TryParse(payload.resultCode, out code)) {
  1943. OnPageFinished(this, code, payload.data);
  1944. } else {
  1945. UniWebViewLogger.Instance.Critical("Invalid status code received: " + payload.resultCode);
  1946. }
  1947. }
  1948. }
  1949. internal void InternalOnPageStarted(string url) {
  1950. if (OnPageStarted != null) {
  1951. OnPageStarted(this, url);
  1952. }
  1953. }
  1954. internal void InternalOnPageErrorReceived(UniWebViewNativeResultPayload payload) {
  1955. if (OnLoadingErrorReceived != null) {
  1956. if (int.TryParse(payload.resultCode, out var code)) {
  1957. OnLoadingErrorReceived(this, code, payload.data, payload);
  1958. } else {
  1959. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  1960. }
  1961. } else if (OnPageErrorReceived != null) {
  1962. if (int.TryParse(payload.resultCode, out var code)) {
  1963. OnPageErrorReceived(this, code, payload.data);
  1964. } else {
  1965. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  1966. }
  1967. }
  1968. }
  1969. internal void InternalOnPageProgressChanged(float progress) {
  1970. if (OnPageProgressChanged != null) {
  1971. OnPageProgressChanged(this, progress);
  1972. }
  1973. }
  1974. internal void InternalOnMessageReceived(string result) {
  1975. if (OnMessageReceived != null) {
  1976. var message = new UniWebViewMessage(result);
  1977. OnMessageReceived(this, message);
  1978. }
  1979. }
  1980. internal void InternalOnShouldClose() {
  1981. if (OnShouldClose != null) {
  1982. var shouldClose = OnShouldClose(this);
  1983. if (shouldClose) {
  1984. Destroy(this);
  1985. }
  1986. } else {
  1987. Destroy(this);
  1988. }
  1989. }
  1990. internal void InternalOnWebContentProcessDidTerminate() {
  1991. if (OnWebContentProcessTerminated != null) {
  1992. OnWebContentProcessTerminated(this);
  1993. }
  1994. }
  1995. internal void InternalOnMultipleWindowOpened(string multiWindowId) {
  1996. if (OnMultipleWindowOpened != null) {
  1997. OnMultipleWindowOpened(this, multiWindowId);
  1998. }
  1999. }
  2000. internal void InternalOnMultipleWindowClosed(string multiWindowId) {
  2001. if (OnMultipleWindowClosed != null) {
  2002. OnMultipleWindowClosed(this, multiWindowId);
  2003. }
  2004. }
  2005. internal void InternalOnFileDownloadStarted(UniWebViewNativeResultPayload payload) {
  2006. if (OnFileDownloadStarted != null) {
  2007. OnFileDownloadStarted(this, payload.identifier, payload.data);
  2008. }
  2009. }
  2010. internal void InternalOnFileDownloadFinished(UniWebViewNativeResultPayload payload) {
  2011. if (OnFileDownloadFinished != null) {
  2012. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  2013. OnFileDownloadFinished(this, errorCode, payload.identifier, payload.data);
  2014. }
  2015. }
  2016. internal void InternalOnCaptureSnapshotFinished(UniWebViewNativeResultPayload payload) {
  2017. if (OnCaptureSnapshotFinished != null) {
  2018. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  2019. OnCaptureSnapshotFinished(this, errorCode, payload.data);
  2020. }
  2021. }
  2022. internal void InternalOnSnapshotRenderingStarted(string identifier) {
  2023. Action action;
  2024. if (actions.TryGetValue(identifier, out action)) {
  2025. action();
  2026. actions.Remove(identifier);
  2027. }
  2028. }
  2029. /// <summary>
  2030. /// Sets whether the web view should behave in immersive mode, that is,
  2031. /// hides the status bar and navigation bar with a sticky style.
  2032. ///
  2033. /// This method is only for Android. Default is enabled.
  2034. /// </summary>
  2035. /// <param name="enabled"></param>
  2036. [Obsolete("SetImmersiveModeEnabled is deprecated. Now UniWebView always respect navigation bar/status bar settings from Unity.", false)]
  2037. public void SetImmersiveModeEnabled(bool enabled) {
  2038. Debug.LogError(
  2039. "SetImmersiveModeEnabled is removed in UniWebView 4." +
  2040. "Now UniWebView always respect navigation bar/status bar settings from Unity."
  2041. );
  2042. }
  2043. /// <summary>
  2044. /// Delegate for code keycode received event.
  2045. /// </summary>
  2046. /// <param name="webView">The web view component which raises this event.</param>
  2047. /// <param name="keyCode">The key code of pressed key. See [Android API for keycode](https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_0) to know the possible values.</param>
  2048. [Obsolete("KeyCodeReceivedDelegate is deprecated. Now UniWebView never intercepts device key code events. Check `Input.GetKeyUp` instead.", false)]
  2049. public delegate void KeyCodeReceivedDelegate(UniWebView webView, int keyCode);
  2050. /// <summary>
  2051. /// Raised when a key (like back button or volume up) on the device is pressed.
  2052. ///
  2053. /// This event only raised on Android. It is useful when you disabled the back button but still need to
  2054. /// get the back button event. On iOS, user's key action is not avaliable and this event will never be
  2055. /// raised.
  2056. /// </summary>
  2057. [Obsolete("OnKeyCodeReceived is deprecated and never called. Now UniWebView never intercepts device key code events. Check `Input.GetKeyUp` instead.", false)]
  2058. #pragma warning disable CS0067
  2059. public event KeyCodeReceivedDelegate OnKeyCodeReceived;
  2060. }