UniWebView.Event.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. //
  2. // UniWebView.Event.cs
  3. // Created by Wang Wei (@onevcat) on 2025-04-19.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // “as is” basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using System;
  18. using UnityEngine;
  19. // UniWebView Event related part
  20. public partial class UniWebView {
  21. /// <summary>
  22. /// Delegate for page started event.
  23. /// </summary>
  24. /// <param name="webView">The web view component which raises this event.</param>
  25. /// <param name="url">The url which the web view is about to load.</param>
  26. public delegate void PageStartedDelegate(UniWebView webView, string url);
  27. /// <summary>
  28. /// Raised when the web view starts loading a url.
  29. ///
  30. /// This event will be invoked for both url loading with `Load` method or by a link navigating from page.
  31. /// </summary>
  32. public event PageStartedDelegate OnPageStarted;
  33. /// <summary>
  34. /// Delegate for page committed event.
  35. /// </summary>
  36. /// <param name="webView">The web view component which raises this event.</param>
  37. /// <param name="url">The url which the web view has started receiving content for.</param>
  38. public delegate void PageCommittedDelegate(UniWebView webView, string url);
  39. /// <summary>
  40. /// Raised when the web view receives response from the server and starts receiving web content.
  41. ///
  42. /// This event will be invoked when the web view has confirmed the response is a web page and
  43. /// has started to receive and process the web content. This happens after `OnPageStarted` but
  44. /// before `OnPageFinished`.
  45. ///
  46. /// This is an ideal place to inject JavaScript code at the earliest possible moment when a page starts loading.
  47. /// Note that JavaScript execution is asynchronous - it may complete after the page finishes loading.
  48. /// For most cases, it is recommended to use `OnPageFinished` event instead, which ensures the page is fully loaded.
  49. /// </summary>
  50. public event PageCommittedDelegate OnPageCommitted;
  51. /// <summary>
  52. /// Delegate for page finished event.
  53. /// </summary>
  54. /// <param name="webView">The web view component which raises this event.</param>
  55. /// <param name="statusCode">HTTP status code received from response.</param>
  56. /// <param name="url">The url which the web view loaded.</param>
  57. public delegate void PageFinishedDelegate(UniWebView webView, int statusCode, string url);
  58. /// <summary>
  59. /// Raised when the web view finished to load a url successfully.
  60. ///
  61. /// This method will be invoked when a valid response received from the url, regardless of the response status.
  62. /// If a url loading fails before reaching to the server and getting a response, `OnLoadingErrorReceived` will be
  63. /// raised instead.
  64. /// </summary>
  65. public event PageFinishedDelegate OnPageFinished;
  66. /// <summary>
  67. /// Delegate for page loading error received event.
  68. /// </summary>
  69. /// <param name="webView">The web view component which raises this event.</param>
  70. /// <param name="errorCode">
  71. /// The error code which indicates the error type.
  72. /// It can be different from systems and platforms.
  73. /// </param>
  74. /// <param name="errorMessage">The error message which indicates the error.</param>
  75. /// <param name="payload">The payload received from native side, which contains the error information, such as the failing URL, in its `Extra`.</param>
  76. public delegate void LoadingErrorReceivedDelegate(
  77. UniWebView webView,
  78. int errorCode,
  79. string errorMessage,
  80. UniWebViewNativeResultPayload payload);
  81. /// <summary>
  82. /// Raised when an error encountered during the loading process.
  83. /// Such as the "host not found" error or "no Internet connection" error will raise this event.
  84. ///
  85. /// </summary>
  86. public event LoadingErrorReceivedDelegate OnLoadingErrorReceived;
  87. /// <summary>
  88. /// Delegate for page progress changed event.
  89. /// </summary>
  90. /// <param name="webView">The web view component which raises this event.</param>
  91. /// <param name="progress">A value indicates the loading progress of current page. It is a value between 0.0f and 1.0f.</param>
  92. public delegate void PageProgressChangedDelegate(UniWebView webView, float progress);
  93. /// <summary>
  94. /// Raised when the loading progress value changes in current web view.
  95. /// </summary>
  96. public event PageProgressChangedDelegate OnPageProgressChanged;
  97. /// <summary>
  98. /// Delegate for message received event.
  99. /// </summary>
  100. /// <param name="webView">The web view component which raises this event.</param>
  101. /// <param name="message">Message received from web view.</param>
  102. public delegate void MessageReceivedDelegate(UniWebView webView, UniWebViewMessage message);
  103. /// <summary>
  104. /// Raised when a message from web view is received.
  105. ///
  106. /// Generally, the message comes from a navigation to
  107. /// a scheme which is observed by current web view. You could use `AddUrlScheme` and
  108. /// `RemoveUrlScheme` to manipulate the scheme list.
  109. ///
  110. /// "uniwebview://" scheme is default in the list, so a clicking on link starting with "uniwebview://"
  111. /// will raise this event, if it is not removed.
  112. /// </summary>
  113. public event MessageReceivedDelegate OnMessageReceived;
  114. /// <summary>
  115. /// Delegate for should close event.
  116. /// </summary>
  117. /// <param name="webView">The web view component which raises this event.</param>
  118. /// <returns>Whether the web view should be closed and destroyed.</returns>
  119. public delegate bool ShouldCloseDelegate(UniWebView webView);
  120. /// <summary>
  121. /// Raised when the web view is about to close itself.
  122. ///
  123. /// This event is raised when the users close the web view by Back button on Android, Done button on iOS,
  124. /// or Close button on Unity Editor. It gives a chance to make final decision whether the web view should
  125. /// be closed and destroyed. You can also clean all related resources you created (such as a reference to
  126. /// the web view) in this event.
  127. /// </summary>
  128. public event ShouldCloseDelegate OnShouldClose;
  129. /// <summary>
  130. /// Delegate for orientation changed event.
  131. /// </summary>
  132. /// <param name="webView">The web view component which raises this event.</param>
  133. /// <param name="orientation">The screen orientation for current state.</param>
  134. public delegate void OrientationChangedDelegate(UniWebView webView, ScreenOrientation orientation);
  135. /// <summary>
  136. /// Raised when the screen orientation is changed. It is a good time to set the web view frame if you
  137. /// need to support multiple orientations in your game.
  138. /// </summary>
  139. public event OrientationChangedDelegate OnOrientationChanged;
  140. /// <summary>
  141. /// Delegate for content loading terminated event.
  142. /// </summary>
  143. /// <param name="webView">The web view component which raises this event.</param>
  144. public delegate void OnWebContentProcessTerminatedDelegate(UniWebView webView);
  145. /// <summary>
  146. /// On iOS, raise when the system calls `webViewWebContentProcessDidTerminate` method. On Android, raise when the
  147. /// system calls `onRenderProcessGone` method.
  148. ///
  149. /// It is usually due to a low memory or the render process crashes when loading the web content. When this happens,
  150. /// the web view will leave you a blank white screen.
  151. ///
  152. /// Usually you should close the web view and clean all the resource since there is no good way to restore. In some
  153. /// cases, you can also try to free as much as memory and do a page `Reload`.
  154. /// </summary>
  155. public event OnWebContentProcessTerminatedDelegate OnWebContentProcessTerminated;
  156. /// <summary>
  157. /// Delegate for file download task starting event.
  158. /// </summary>
  159. /// <param name="webView">The web view component which raises this event.</param>
  160. /// <param name="remoteUrl">The remote URL of this download task. This is also the download URL for the task.</param>
  161. /// <param name="fileName">The file name which user chooses to use.</param>
  162. public delegate void FileDownloadStarted(UniWebView webView, string remoteUrl, string fileName);
  163. /// <summary>
  164. /// Raised when a file download task starts.
  165. /// </summary>
  166. public event FileDownloadStarted OnFileDownloadStarted;
  167. /// <summary>
  168. /// Delegate for file download task finishing event.
  169. /// </summary>
  170. /// <param name="webView">The web view component which raises this event.</param>
  171. /// <param name="errorCode">
  172. /// The error code of the download task result. Value `0` means the download finishes without a problem.
  173. /// Any other non-`0` value indicates an issue. The detail meaning of the error code depends on system.
  174. /// On iOS, it is usually the `errorCode` of the received `NSURLError`. On Android, the value usually represents
  175. /// an `ERROR_*` value in `DownloadManager`.
  176. /// </param>
  177. /// <param name="remoteUrl">The remote URL of this download task.</param>
  178. /// <param name="diskPath">
  179. /// The file path of the downloaded file. On iOS, the downloader file is in a temporary folder of your app sandbox.
  180. /// On Android, it is in the "Download" folder of your app.
  181. /// </param>
  182. public delegate void FileDownloadFinished(UniWebView webView, int errorCode, string remoteUrl, string diskPath);
  183. /// <summary>
  184. /// Raised when a file download task finishes with either an error or success.
  185. /// </summary>
  186. public event FileDownloadFinished OnFileDownloadFinished;
  187. /// <summary>
  188. /// Delegate for capturing snapshot finished event.
  189. /// </summary>
  190. /// <param name="webView">The web view component which raises this event.</param>
  191. /// <param name="errorCode">
  192. /// The error code of the event. If the snapshot is captured and stored without a problem, the error code is 0.
  193. /// Any other number indicates an error happened. In most cases, the screenshot capturing only fails due to lack
  194. /// of disk storage.
  195. /// </param>
  196. /// <param name="diskPath">
  197. /// An accessible disk path to the captured snapshot image. If an error happens, it is an empty string.
  198. /// </param>
  199. public delegate void CaptureSnapshotFinished(UniWebView webView, int errorCode, string diskPath);
  200. /// <summary>
  201. /// Raised when an image captured and stored in a cache path on disk.
  202. /// </summary>
  203. public event CaptureSnapshotFinished OnCaptureSnapshotFinished;
  204. /// <summary>
  205. /// Delegate for multiple window opening event.
  206. /// </summary>
  207. /// <param name="webView">The web view component which opens the new multiple (pop-up) window.</param>
  208. /// <param name="multipleWindowId">The identifier of the opened new window.</param>
  209. public delegate void MultipleWindowOpenedDelegate(UniWebView webView, string multipleWindowId);
  210. /// <summary>
  211. /// Raised when a new window is opened. This happens when you enable the `SetSupportMultipleWindows` and open a
  212. /// new pop-up window.
  213. /// </summary>
  214. public event MultipleWindowOpenedDelegate OnMultipleWindowOpened;
  215. /// <summary>
  216. /// Delegate for popup window opening event.
  217. /// </summary>
  218. /// <param name="webView">The web view component which opens the popup window.</param>
  219. /// <param name="popup">The popup window handle.</param>
  220. public delegate void PopupWindowOpenedDelegate(UniWebView webView, UniWebViewPopup popup);
  221. /// <summary>
  222. /// Raised when a popup window is opened. This provides a lightweight popup handle.
  223. /// </summary>
  224. public event PopupWindowOpenedDelegate OnPopupWindowOpened;
  225. /// <summary>
  226. /// Delegate for multiple window closing event.
  227. /// </summary>
  228. /// <param name="webView">The web view component which closes the multiple window.</param>
  229. /// <param name="multipleWindowId">The identifier of the closed window.</param>
  230. public delegate void MultipleWindowClosedDelegate(UniWebView webView, string multipleWindowId);
  231. /// <summary>
  232. /// Raised when the multiple window is closed. This happens when the pop-up window is closed by navigation operation
  233. /// or by a invocation of `close()` on the page.
  234. /// </summary>
  235. public event MultipleWindowClosedDelegate OnMultipleWindowClosed;
  236. /// <summary>
  237. /// Delegate for popup window closing event.
  238. /// </summary>
  239. /// <param name="webView">The web view component which closes the popup window.</param>
  240. /// <param name="popup">The popup window handle.</param>
  241. public delegate void PopupWindowClosedDelegate(UniWebView webView, UniWebViewPopup popup);
  242. /// <summary>
  243. /// Raised when a popup window is closed.
  244. /// </summary>
  245. public event PopupWindowClosedDelegate OnPopupWindowClosed;
  246. /// <summary>
  247. /// Delegate for external activity result received event.
  248. /// </summary>
  249. /// <param name="webView">The web view component which raises this event.</param>
  250. /// <param name="result">The result returned from the external Android activity.</param>
  251. public delegate void ExternalActivityResultReceivedDelegate(
  252. UniWebView webView, UniWebViewExternalActivityResult result);
  253. /// <summary>
  254. /// Raised when an external Android activity, launched from the web view via a custom URL scheme
  255. /// (such as `upi://` for payment apps), finishes and returns a result.
  256. ///
  257. /// When a web page navigates to a non-HTTP URL scheme that matches an installed app, UniWebView
  258. /// launches that app using Android's `startActivityForResult`. When the external app calls
  259. /// `setResult` and finishes, this event delivers the result back to your Unity code.
  260. ///
  261. /// This event is only available on Android. On iOS and macOS, external app communication uses
  262. /// URL schemes and deep links instead (handle via `Application.deepLinkActivated`).
  263. /// </summary>
  264. public event ExternalActivityResultReceivedDelegate OnExternalActivityResultReceived;
  265. /// <summary>
  266. /// Delegate for channel message received event.
  267. /// </summary>
  268. /// <param name="webView">The web view component which raises this event.</param>
  269. /// <param name="message">The channel message received from JavaScript Bridge.</param>
  270. /// <returns>A response object that will be sent back to JavaScript. For sync calls, this is the immediate response. For async calls that don't need a response, this can be null.</returns>
  271. public delegate UniWebViewChannelMessageResponse ChannelMessageReceivedDelegate(UniWebView webView, UniWebViewChannelMessage message);
  272. /// <summary>
  273. /// Raised when a channel message from JavaScript Bridge is received.
  274. ///
  275. /// This event is triggered when JavaScript code calls window.uniwebview.send(),
  276. /// window.uniwebview.call(), or window.uniwebview.request(). The handler should
  277. /// return a UniWebViewChannelMessageResponse for sync calls or when immediate response
  278. /// is needed. For async messages that need delayed response, use message.Respond() method.
  279. /// </summary>
  280. public event ChannelMessageReceivedDelegate OnChannelMessageReceived;
  281. /* //////////////////////////////////////////////////////
  282. // Internal Listener Interface
  283. ////////////////////////////////////////////////////// */
  284. internal void InternalOnPageStarted(string url) {
  285. if (OnPageStarted != null) {
  286. OnPageStarted(this, url);
  287. }
  288. }
  289. internal void InternalOnShowTransitionFinished(string identifier) {
  290. Action action;
  291. if (actions.TryGetValue(identifier, out action)) {
  292. action();
  293. actions.Remove(identifier);
  294. }
  295. }
  296. internal void InternalOnHideTransitionFinished(string identifier) {
  297. Action action;
  298. if (actions.TryGetValue(identifier, out action)) {
  299. action();
  300. actions.Remove(identifier);
  301. }
  302. }
  303. internal void InternalOnAnimateToFinished(string identifier) {
  304. Action action;
  305. if (actions.TryGetValue(identifier, out action)) {
  306. action();
  307. actions.Remove(identifier);
  308. }
  309. }
  310. internal void InternalOnGeneralCallback(string identifier) {
  311. Action action;
  312. if (actions.TryGetValue(identifier, out action)) {
  313. action();
  314. actions.Remove(identifier);
  315. }
  316. }
  317. internal void InternalOnAddJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  318. Action<UniWebViewNativeResultPayload> action;
  319. var identifier = payload.identifier;
  320. if (payloadActions.TryGetValue(identifier, out action)) {
  321. action(payload);
  322. payloadActions.Remove(identifier);
  323. }
  324. }
  325. internal void InternalOnEvalJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  326. Action<UniWebViewNativeResultPayload> action;
  327. var identifier = payload.identifier;
  328. if (payloadActions.TryGetValue(identifier, out action)) {
  329. action(payload);
  330. payloadActions.Remove(identifier);
  331. }
  332. }
  333. internal void InternalOnPageFinished(UniWebViewNativeResultPayload payload) {
  334. if (OnPageFinished != null) {
  335. int code = -1;
  336. if (int.TryParse(payload.resultCode, out code)) {
  337. OnPageFinished(this, code, payload.data);
  338. } else {
  339. UniWebViewLogger.Instance.Critical("Invalid status code received: " + payload.resultCode);
  340. }
  341. }
  342. }
  343. internal void InternalOnPageCommitted(string url) {
  344. if (OnPageCommitted != null) {
  345. OnPageCommitted(this, url);
  346. }
  347. }
  348. internal void InternalOnPageErrorReceived(UniWebViewNativeResultPayload payload) {
  349. if (OnLoadingErrorReceived != null) {
  350. if (int.TryParse(payload.resultCode, out var code)) {
  351. OnLoadingErrorReceived(this, code, payload.data, payload);
  352. } else {
  353. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  354. }
  355. } else if (OnPageErrorReceived != null) {
  356. if (int.TryParse(payload.resultCode, out var code)) {
  357. OnPageErrorReceived(this, code, payload.data);
  358. } else {
  359. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  360. }
  361. }
  362. }
  363. internal void InternalOnPageProgressChanged(float progress) {
  364. if (OnPageProgressChanged != null) {
  365. OnPageProgressChanged(this, progress);
  366. }
  367. }
  368. internal void InternalOnMessageReceived(string result) {
  369. if (OnMessageReceived != null) {
  370. var message = new UniWebViewMessage(result);
  371. OnMessageReceived(this, message);
  372. }
  373. }
  374. internal void InternalOnShouldClose() {
  375. if (OnShouldClose != null) {
  376. var shouldClose = OnShouldClose(this);
  377. if (shouldClose) {
  378. Destroy(this);
  379. }
  380. } else {
  381. Destroy(this);
  382. }
  383. }
  384. internal void InternalOnWebContentProcessDidTerminate() {
  385. if (OnWebContentProcessTerminated != null) {
  386. OnWebContentProcessTerminated(this);
  387. }
  388. }
  389. internal void InternalOnMultipleWindowOpened(string multiWindowId) {
  390. var popup = GetOrCreatePopupWindow(multiWindowId);
  391. if (OnMultipleWindowOpened != null) {
  392. OnMultipleWindowOpened(this, multiWindowId);
  393. }
  394. if (OnPopupWindowOpened != null) {
  395. OnPopupWindowOpened(this, popup);
  396. }
  397. }
  398. internal void InternalOnMultipleWindowClosed(string multiWindowId) {
  399. HandlePopupWindowClosed(multiWindowId);
  400. }
  401. internal void InternalOnFileDownloadStarted(UniWebViewNativeResultPayload payload) {
  402. if (OnFileDownloadStarted != null) {
  403. OnFileDownloadStarted(this, payload.identifier, payload.data);
  404. }
  405. }
  406. internal void InternalOnFileDownloadFinished(UniWebViewNativeResultPayload payload) {
  407. if (OnFileDownloadFinished != null) {
  408. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  409. OnFileDownloadFinished(this, errorCode, payload.identifier, payload.data);
  410. }
  411. }
  412. internal void InternalOnCaptureSnapshotFinished(UniWebViewNativeResultPayload payload) {
  413. if (OnCaptureSnapshotFinished != null) {
  414. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  415. OnCaptureSnapshotFinished(this, errorCode, payload.data);
  416. }
  417. }
  418. internal void InternalOnIntentResultReceived(UniWebViewNativeResultPayload payload) {
  419. if (OnExternalActivityResultReceived != null) {
  420. int resultCode = int.TryParse(payload.resultCode, out resultCode) ? resultCode : 0;
  421. var result = new UniWebViewExternalActivityResult(payload.identifier, resultCode, payload.data);
  422. OnExternalActivityResultReceived(this, result);
  423. }
  424. }
  425. internal void InternalOnSnapshotRenderingStarted(string identifier) {
  426. if (string.IsNullOrEmpty(identifier)) {
  427. return;
  428. }
  429. if (!actions.TryGetValue(identifier, out var action)) {
  430. return;
  431. }
  432. action();
  433. actions.Remove(identifier);
  434. }
  435. internal static void InternalCookieOperation(UniWebViewNativeResultPayload payload) {
  436. var identifier = payload.identifier;
  437. if (!globalPayloadActions.TryGetValue(identifier, out var action)) {
  438. return;
  439. }
  440. action(payload);
  441. globalPayloadActions.Remove(identifier);
  442. }
  443. }