UniWebView.cs 34 KB

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