UniWebViewChannelMessage.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. //
  2. // UniWebViewChannelMessage.cs
  3. // Created by Wang Wei(@onevcat) on 2025-08-02.
  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 UniWebViewExternal;
  19. /// <summary>
  20. /// Channel message types corresponding to different JavaScript call methods
  21. /// </summary>
  22. public enum UniWebViewChannelMessageType {
  23. /// <summary>
  24. /// Fire-and-forget message (window.uniwebview.send)
  25. /// </summary>
  26. Send = 0,
  27. /// <summary>
  28. /// Synchronous call with immediate response (window.uniwebview.call)
  29. /// </summary>
  30. Call = 1,
  31. /// <summary>
  32. /// Asynchronous request with promise-based response (window.uniwebview.request)
  33. /// </summary>
  34. Request = 2
  35. }
  36. /// <summary>
  37. /// Response delegate for async messages
  38. /// </summary>
  39. /// <param name="messageId">The message ID to respond to</param>
  40. /// <param name="responseJson">The response Json string to send back</param>
  41. public delegate void ChannelMessageRespondDelegate(string messageId, UniWebViewChannelMessageResponse response);
  42. /// <summary>
  43. /// Represents a channel message received from the web view's JavaScript Bridge
  44. /// </summary>
  45. [Serializable]
  46. public class UniWebViewChannelMessage {
  47. /// <summary>
  48. /// Unique identifier for this message
  49. /// </summary>
  50. public string id;
  51. /// <summary>
  52. /// Timestamp when the message was created (Unix milliseconds)
  53. /// </summary>
  54. public long timestamp;
  55. /// <summary>
  56. /// The action type for this message (required)
  57. /// </summary>
  58. public string action;
  59. /// <summary>
  60. /// The message data as a JSON string (optional)
  61. /// </summary>
  62. public string data;
  63. /// <summary>
  64. /// The type of this channel message (send/call/request)
  65. /// </summary>
  66. public int messageType;
  67. // Non-serialized delegate for async responses
  68. [System.NonSerialized]
  69. private ChannelMessageRespondDelegate _respondDelegate;
  70. // Internal constructor with respond delegate
  71. internal UniWebViewChannelMessage(string id, long timestamp, string action, string data, int messageType, ChannelMessageRespondDelegate respondDelegate) {
  72. this.id = id;
  73. this.timestamp = timestamp;
  74. this.action = action;
  75. this.data = data;
  76. this.messageType = messageType;
  77. this._respondDelegate = respondDelegate;
  78. }
  79. // Default constructor for JSON deserialization
  80. public UniWebViewChannelMessage() { }
  81. /// <summary>
  82. /// Gets the strongly-typed message type
  83. /// </summary>
  84. public UniWebViewChannelMessageType MessageType => (UniWebViewChannelMessageType)messageType;
  85. /// <summary>
  86. /// True if this is a fire-and-forget message (send)
  87. /// </summary>
  88. public bool isFireAndForget => MessageType == UniWebViewChannelMessageType.Send;
  89. /// <summary>
  90. /// True if this is a synchronous call (call)
  91. /// </summary>
  92. public bool isSyncCall => MessageType == UniWebViewChannelMessageType.Call;
  93. /// <summary>
  94. /// True if this is an asynchronous request (request)
  95. /// </summary>
  96. public bool isAsyncRequest => MessageType == UniWebViewChannelMessageType.Request;
  97. public bool TryGetData<T>(out T result) {
  98. result = default;
  99. try {
  100. result = UniWebViewJsonUtility.FromJson<T>(data);
  101. return true;
  102. } catch (Exception e) {
  103. UniWebViewLogger.Instance.Critical(() => $"Failed to parse message data for action '{action}': {e.Message}");
  104. return false;
  105. }
  106. }
  107. public T GetData<T>() {
  108. if (TryGetData<T>(out var result)) {
  109. return result;
  110. }
  111. return default(T);
  112. }
  113. // ReSharper disable Unity.PerformanceAnalysis
  114. /// <summary>
  115. /// Sends an async response for this message
  116. /// </summary>
  117. /// <param name="response">The response to send back</param>
  118. public void Respond(UniWebViewChannelMessageResponse response) {
  119. if (!isAsyncRequest) {
  120. UniWebViewLogger.Instance.Critical(() => $"Cannot respond to a {MessageType} message. Only Request messages support async responses.");
  121. return;
  122. }
  123. if (_respondDelegate == null) {
  124. UniWebViewLogger.Instance.Critical(() => "Cannot respond: Response delegate is null (message may have been deserialized or webview destroyed)");
  125. return;
  126. }
  127. _respondDelegate(id, response);
  128. }
  129. /// <summary>
  130. /// Convenience method for success responses
  131. /// </summary>
  132. /// <param name="data">The data to send back</param>
  133. public void Respond(object data) {
  134. Respond(UniWebViewChannelMessageResponse.Success(data));
  135. }
  136. /// <summary>
  137. /// Convenience method for error responses
  138. /// </summary>
  139. /// <param name="errorData">The error data to send back (supports any JSON-compatible type)</param>
  140. public void RespondError(object errorData) {
  141. Respond(UniWebViewChannelMessageResponse.Error(errorData));
  142. }
  143. }
  144. /// <summary>
  145. /// Represents a response for a channel message
  146. /// </summary>
  147. public class UniWebViewChannelMessageResponse {
  148. [Serializable]
  149. class ResultWrapper {
  150. public string result;
  151. }
  152. [Serializable]
  153. class ErrorWrapper {
  154. public string error;
  155. }
  156. /// <summary>
  157. /// Response data
  158. /// </summary>
  159. public object data;
  160. /// <summary>
  161. /// Whether this response represents an error
  162. /// </summary>
  163. public bool hasError;
  164. /// <summary>
  165. /// Error data if hasError is true (supports any JSON-compatible type)
  166. /// </summary>
  167. public object errorData;
  168. /// <summary>
  169. /// Creates a success response
  170. /// </summary>
  171. /// <param name="data">The data to include in the response</param>
  172. public UniWebViewChannelMessageResponse(object data) {
  173. this.data = data;
  174. this.hasError = false;
  175. this.errorData = null;
  176. }
  177. /// <summary>
  178. /// Creates an error response
  179. /// </summary>
  180. /// <param name="errorData">The error data (supports any JSON-compatible type)</param>
  181. private UniWebViewChannelMessageResponse(object errorData, bool isError) {
  182. this.data = null;
  183. this.hasError = true;
  184. this.errorData = errorData;
  185. }
  186. internal string ToJson() {
  187. if (hasError) {
  188. return UniWebViewJsonUtility.ToJson(new ErrorWrapper { error = UniWebViewJsonUtility.ToJson(errorData) });
  189. } else {
  190. return UniWebViewJsonUtility.ToJson(new ResultWrapper { result = UniWebViewJsonUtility.ToJson(data) });
  191. }
  192. }
  193. /// <summary>
  194. /// Static factory method for success responses
  195. /// </summary>
  196. /// <param name="data">The data to include</param>
  197. /// <returns>A success response</returns>
  198. public static UniWebViewChannelMessageResponse Success(object data) {
  199. return new UniWebViewChannelMessageResponse(data);
  200. }
  201. /// <summary>
  202. /// Static factory method for error responses
  203. /// </summary>
  204. /// <param name="errorData">The error data (supports any JSON-compatible type)</param>
  205. /// <returns>An error response</returns>
  206. public static UniWebViewChannelMessageResponse Error(object errorData) {
  207. return new UniWebViewChannelMessageResponse(errorData, true);
  208. }
  209. }