using System; using UnityEngine; using UnityEngine.UI; [DisallowMultipleComponent] public sealed class ActivityWebViewController : MonoBehaviour { const float RestoredBackdropAlpha = 0.68f; const float MaximizedBackdropAlpha = 1.0f; static ActivityWebViewController instance; static bool shownDuringLoadingThisSession; static bool shownThisSession; UniWebView webView; Image backdrop; float initialScale = 0.8f; bool maximized; bool closing; bool pageLoaded; Rect lastSafeArea; int lastScreenWidth; int lastScreenHeight; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetStatics() { instance = null; shownDuringLoadingThisSession = false; shownThisSession = false; } public static void ShowDuringLoading() { if (shownDuringLoadingThisSession) return; ActivityWebViewSettings settings = ActivityWebViewSettings.Instance; if (settings == null) { Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources."); return; } if (!settings.showOnLaunch) return; if (EnsureInstance()) { shownDuringLoadingThisSession = true; Debug.Log("[Activity] Activity page opened during loading."); } } public static void ShowOnLaunch() { if (shownThisSession) return; ActivityWebViewSettings settings = ActivityWebViewSettings.Instance; if (settings == null) { Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources."); return; } if (!settings.showOnLaunch) return; if (Show()) shownThisSession = true; } public static bool Show() { return EnsureInstance(); } static bool EnsureInstance() { if (instance != null) { instance.ApplyCurrentFrame(); if (instance.webView != null && instance.pageLoaded) instance.webView.Show(); return true; } ActivityWebViewSettings settings = ActivityWebViewSettings.Instance; string url = settings != null ? settings.activityUrl : ActivityWebViewSettings.DefaultActivityUrl; url = string.IsNullOrWhiteSpace(url) ? ActivityWebViewSettings.DefaultActivityUrl : url.Trim(); if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) { Debug.LogWarning("[Activity] Activity URL must be an absolute HTTP(S) URL: " + url); return false; } if (!UniWebView.IsWebViewSupported) { Debug.LogWarning("[Activity] UniWebView is not supported on this platform."); return false; } var root = new GameObject("ActivityWebView"); DontDestroyOnLoad(root); var controller = root.AddComponent(); controller.Initialize(url, settings != null ? settings.initialScale : 0.8f); return true; } public static void CloseCurrent() { if (instance != null) instance.Close(); } void Initialize(string url, float scale) { instance = this; initialScale = Mathf.Clamp(scale, 0.1f, 1f); CreateBackdrop(); CreateWebView(); lastSafeArea = Screen.safeArea; lastScreenWidth = Screen.width; lastScreenHeight = Screen.height; ApplyCurrentFrame(); webView.Load(url); } void Update() { if (webView == null) return; Rect safeArea = Screen.safeArea; if (safeArea != lastSafeArea || lastScreenWidth != Screen.width || lastScreenHeight != Screen.height) { lastSafeArea = safeArea; lastScreenWidth = Screen.width; lastScreenHeight = Screen.height; ApplyCurrentFrame(); } } void OnDestroy() { if (webView != null) { webView.OnShouldClose -= HandleShouldClose; webView.OnPageFinished -= HandlePageFinished; webView.OnLoadingErrorReceived -= HandleLoadingError; webView.OnChannelMessageReceived -= HandleChannelMessage; webView.OnMessageReceived -= HandleUrlMessage; } if (instance == this) instance = null; } void CreateBackdrop() { var canvasObject = new GameObject( "Backdrop", typeof(RectTransform), typeof(Canvas), typeof(GraphicRaycaster)); canvasObject.transform.SetParent(transform, false); var canvas = canvasObject.GetComponent(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.sortingOrder = short.MaxValue; var imageObject = new GameObject("Dim", typeof(RectTransform), typeof(Image)); imageObject.transform.SetParent(canvasObject.transform, false); var rect = imageObject.GetComponent(); rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; rect.offsetMin = Vector2.zero; rect.offsetMax = Vector2.zero; backdrop = imageObject.GetComponent(); backdrop.color = new Color(0f, 0f, 0f, RestoredBackdropAlpha); backdrop.raycastTarget = true; } void CreateWebView() { UniWebView.SetAllowAutoPlay(true); UniWebView.SetJavaScriptEnabled(true); webView = gameObject.AddComponent(); webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never); webView.BackgroundColor = Color.black; webView.SetBackButtonEnabled(true); webView.OnShouldClose += HandleShouldClose; webView.OnPageFinished += HandlePageFinished; webView.OnLoadingErrorReceived += HandleLoadingError; webView.OnChannelMessageReceived += HandleChannelMessage; webView.OnMessageReceived += HandleUrlMessage; } bool HandleShouldClose(UniWebView view) { Close(); return false; } void HandlePageFinished(UniWebView view, int statusCode, string url) { pageLoaded = true; Debug.Log("[Activity] Activity page loaded: " + url); ApplyCurrentFrame(); view.Show(); } void HandleLoadingError(UniWebView view, int errorCode, string errorMessage, UniWebViewNativeResultPayload payload) { if (pageLoaded) { Debug.LogWarning($"[Activity] Resource loading error {errorCode}: {errorMessage}"); return; } Debug.LogWarning($"[Activity] Failed to load the activity page {errorCode}: {errorMessage}"); Close(); } UniWebViewChannelMessageResponse HandleChannelMessage(UniWebView view, UniWebViewChannelMessage message) { HandleAction(message.action, message.data); return null; } void HandleUrlMessage(UniWebView view, UniWebViewMessage message) { if (!string.Equals(message.Scheme, "uniwebview", StringComparison.OrdinalIgnoreCase)) return; string payload = null; if (message.Args != null) message.Args.TryGetValue("payload", out payload); HandleAction(message.Path, payload); } void HandleAction(string action, string data) { if (string.IsNullOrWhiteSpace(action)) return; switch (action.Trim().ToLowerInvariant()) { case "close": Close(); break; case "maximize": SetMaximized(true); break; case "restore": SetMaximized(false); break; case "facebook_config": ActivityFacebookService.ApplyConfig(ParseFacebookConfig(data)); break; case "openwindow": OpenWindow(data); break; default: ActivityFacebookService.LogEvent(action, data); break; } } void SetMaximized(bool value) { maximized = value; ApplyCurrentFrame(); } void ApplyCurrentFrame() { if (webView != null) webView.Frame = CalculateFrame(); if (backdrop != null) backdrop.color = new Color(0f, 0f, 0f, maximized ? MaximizedBackdropAlpha : RestoredBackdropAlpha); } Rect CalculateFrame() { Rect safeArea = Screen.safeArea; float safeTop = Screen.height - safeArea.yMax; if (maximized) return new Rect(safeArea.xMin, safeTop, safeArea.width, safeArea.height); float width = safeArea.width * initialScale; float height = safeArea.height * initialScale; float x = safeArea.xMin + (safeArea.width - width) * 0.5f; float y = safeTop + (safeArea.height - height) * 0.5f; return new Rect(x, y, width, height); } void OpenWindow(string data) { if (string.IsNullOrWhiteSpace(data)) return; try { var payload = JsonUtility.FromJson(data); if (payload != null && !string.IsNullOrWhiteSpace(payload.url)) Application.OpenURL(payload.url); } catch (Exception exception) { Debug.LogWarning("[Activity] Invalid openWindow payload: " + exception.Message); } } static ActivityFacebookConfig ParseFacebookConfig(string data) { if (string.IsNullOrWhiteSpace(data)) return null; try { return JsonUtility.FromJson(data); } catch (Exception exception) { Debug.LogWarning("[Activity] Invalid Facebook config: " + exception.Message); return null; } } void Close() { if (closing) return; closing = true; if (instance == this) instance = null; Destroy(gameObject); } #pragma warning disable 0649 [Serializable] sealed class ActivityOpenWindowPayload { public string url; } #pragma warning restore 0649 }