UniWebViewChannelMethodManager.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. //
  2. // UniWebViewChannelMethodManager.cs
  3. // Created by Wang Wei(@onevcat) on 2023-04-21.
  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 System.Collections.Generic;
  19. using System.Linq;
  20. using UnityEngine;
  21. enum UniWebViewChannelMethod {
  22. ShouldUniWebViewHandleRequest,
  23. RequestMediaCapturePermission,
  24. EmbeddedToolbarItemAction,
  25. ChannelMessage
  26. }
  27. class UniWebViewChannelMethodManager {
  28. private static UniWebViewChannelMethodManager instance;
  29. private Dictionary<string, Dictionary<string, Func<object, object>>> channels =
  30. new Dictionary<string, Dictionary<string, Func<object, object>>>();
  31. internal static UniWebViewChannelMethodManager Instance {
  32. get {
  33. if (instance == null) {
  34. instance = new UniWebViewChannelMethodManager();
  35. }
  36. return instance;
  37. }
  38. }
  39. #if UNITY_EDITOR
  40. // When entering Play Mode with domain reload disabled, static state survives across sessions.
  41. // Drop the singleton so channel handlers registered in a previous session (closures capturing
  42. // now-destroyed UniWebView instances) do not accumulate.
  43. internal static void ResetForFastEnterPlayMode() {
  44. instance = null;
  45. }
  46. #endif
  47. internal void RegisterChannelMethod(
  48. string webViewName,
  49. UniWebViewChannelMethod method,
  50. Func<object, object> handler)
  51. {
  52. if (!HasRegisteredChannel(webViewName)) {
  53. channels[webViewName] = new Dictionary<string, Func<object, object>>();
  54. }
  55. var methodName = method.ToString();
  56. channels[webViewName][methodName] = handler;
  57. UniWebViewLogger.Instance.Info(() => $"Channel method is registered for web view: {webViewName}, method: {methodName}");
  58. }
  59. internal void UnregisterChannel(string webViewName) {
  60. if (!HasRegisteredChannel(webViewName)) {
  61. return;
  62. }
  63. channels.Remove(webViewName);
  64. UniWebViewLogger.Instance.Debug(() => $"All channel methods are unregistered for web view: {webViewName}");
  65. }
  66. internal void UnregisterChannelMethod(string webViewName, UniWebViewChannelMethod method) {
  67. var methodName = method.ToString();
  68. if (!HasRegisteredChannel(webViewName)) {
  69. return;
  70. }
  71. channels[webViewName].Remove(methodName);
  72. UniWebViewLogger.Instance.Debug(() => $"Channel method is unregistered for web view: {webViewName}, method: {methodName}");
  73. }
  74. bool HasRegisteredChannel(string webViewName) {
  75. return channels.Keys.Contains(webViewName);
  76. }
  77. bool HasRegisteredMethod(string webViewName, string methodName) {
  78. if (!HasRegisteredChannel(webViewName)) {
  79. return false;
  80. }
  81. return channels[webViewName].Keys.Contains(methodName);
  82. }
  83. internal string InvokeMethod(string webViewName, string methodName, string parameters) {
  84. if (!HasRegisteredMethod(webViewName, methodName)) {
  85. UniWebViewLogger.Instance.Info(() => "There is no handler for the channel method. Ignoring.");
  86. return null;
  87. }
  88. var func = channels[webViewName][methodName];
  89. if (!Enum.TryParse<UniWebViewChannelMethod>(methodName, out var method)) {
  90. UniWebViewLogger.Instance.Info(() => $"Unknown method name: {methodName}. Please check, ignoring.");
  91. return null;
  92. }
  93. UniWebViewLogger.Instance.Verbose(() => $"Channel method invoking received for web view: {webViewName}, method: {methodName}, parameters: {parameters}");
  94. string result;
  95. switch (method) {
  96. case UniWebViewChannelMethod.ShouldUniWebViewHandleRequest: {
  97. // (UniWebViewChannelMethodHandleRequest) -> bool
  98. var input = JsonUtility.FromJson<UniWebViewChannelMethodHandleRequest>(parameters);
  99. bool Func(UniWebViewChannelMethodHandleRequest i) => (bool)func(i);
  100. result = ResultJsonWith(Func(input));
  101. break;
  102. }
  103. case UniWebViewChannelMethod.RequestMediaCapturePermission: {
  104. // (UniWebViewChannelMethodMediaCapturePermission) -> UniWebViewMediaCapturePermissionDecision
  105. var input = JsonUtility.FromJson<UniWebViewChannelMethodMediaCapturePermission>(parameters);
  106. UniWebViewMediaCapturePermissionDecision Func(UniWebViewChannelMethodMediaCapturePermission i) => (UniWebViewMediaCapturePermissionDecision)func(i);
  107. result = ResultJsonWith(Func(input));
  108. break;
  109. }
  110. case UniWebViewChannelMethod.EmbeddedToolbarItemAction: {
  111. // (UniWebViewChannelMethodEmbeddedToolbarItemAction) -> bool
  112. var input = JsonUtility.FromJson<UniWebViewChannelMethodEmbeddedToolbarItemAction>(parameters);
  113. bool Func(UniWebViewChannelMethodEmbeddedToolbarItemAction i) => (bool)func(i);
  114. result = ResultJsonWith(Func(input));
  115. break;
  116. }
  117. case UniWebViewChannelMethod.ChannelMessage: {
  118. // Direct string parameters for channel message
  119. // (UniWebViewChannelMessage) -> JSON object
  120. UniWebViewChannelMessage input;
  121. try {
  122. input = JsonUtility.FromJson<UniWebViewChannelMessage>(parameters);
  123. } catch (System.Exception e) {
  124. UniWebViewLogger.Instance.Critical(() => $"Failed to parse channel message: {e.Message}");
  125. result = null;
  126. break;
  127. }
  128. // Validate required action field
  129. if (string.IsNullOrEmpty(input.action)) {
  130. UniWebViewLogger.Instance.Critical(() => "Channel message missing required 'action' field");
  131. result = null;
  132. break;
  133. }
  134. UniWebViewChannelMessageResponse Func(UniWebViewChannelMessage i) => (UniWebViewChannelMessageResponse)func(i);
  135. var response = Func(input);
  136. if (response == null) {
  137. result = null;
  138. } else {
  139. result = response.ToJson();
  140. }
  141. break;
  142. }
  143. default:
  144. result = null;
  145. break;
  146. }
  147. UniWebViewLogger.Instance.Debug(() => $"Channel method handler responded. Result: {result}");
  148. return result;
  149. }
  150. string ResultJsonWith(bool value) {
  151. return value ? "{\"result\":true}" : "{\"result\":false}";
  152. }
  153. string ResultJsonWith(UniWebViewMediaCapturePermissionDecision decision) {
  154. switch (decision) {
  155. case UniWebViewMediaCapturePermissionDecision.Prompt:
  156. return "{\"result\":\"prompt\"}";
  157. case UniWebViewMediaCapturePermissionDecision.Grant:
  158. return "{\"result\":\"grant\"}";
  159. case UniWebViewMediaCapturePermissionDecision.Deny:
  160. return "{\"result\":\"deny\"}";
  161. default:
  162. UniWebViewLogger.Instance.Critical(() => $"Unknown decision: {decision}");
  163. break;
  164. }
  165. Debug.LogAssertion("Unrecognized UniWebViewMediaCapturePermissionDecision. Fallback to prompt.");
  166. return "{\"result\":\"prompt\"}";
  167. }
  168. }