//
// UniWebViewChannelMessage.cs
// Created by Wang Wei(@onevcat) on 2025-08-02.
//
// This file is a part of UniWebView Project (https://uniwebview.com)
// By purchasing the asset, you are allowed to use this code in as many as projects
// you want, only if you publish the final products under the name of the same account
// used for the purchase.
//
// This asset and all corresponding files (such as source code) are provided on an
// "as is" basis, without warranty of any kind, express of implied, including but not
// limited to the warranties of merchantability, fitness for a particular purpose, and
// noninfringement. In no event shall the authors or copyright holders be liable for any
// claim, damages or other liability, whether in action of contract, tort or otherwise,
// arising from, out of or in connection with the software or the use of other dealing in the software.
//
using System;
using UniWebViewExternal;
///
/// Channel message types corresponding to different JavaScript call methods
///
public enum UniWebViewChannelMessageType {
///
/// Fire-and-forget message (window.uniwebview.send)
///
Send = 0,
///
/// Synchronous call with immediate response (window.uniwebview.call)
///
Call = 1,
///
/// Asynchronous request with promise-based response (window.uniwebview.request)
///
Request = 2
}
///
/// Response delegate for async messages
///
/// The message ID to respond to
/// The response Json string to send back
public delegate void ChannelMessageRespondDelegate(string messageId, UniWebViewChannelMessageResponse response);
///
/// Represents a channel message received from the web view's JavaScript Bridge
///
[Serializable]
public class UniWebViewChannelMessage {
///
/// Unique identifier for this message
///
public string id;
///
/// Timestamp when the message was created (Unix milliseconds)
///
public long timestamp;
///
/// The action type for this message (required)
///
public string action;
///
/// The message data as a JSON string (optional)
///
public string data;
///
/// The type of this channel message (send/call/request)
///
public int messageType;
// Non-serialized delegate for async responses
[System.NonSerialized]
private ChannelMessageRespondDelegate _respondDelegate;
// Internal constructor with respond delegate
internal UniWebViewChannelMessage(string id, long timestamp, string action, string data, int messageType, ChannelMessageRespondDelegate respondDelegate) {
this.id = id;
this.timestamp = timestamp;
this.action = action;
this.data = data;
this.messageType = messageType;
this._respondDelegate = respondDelegate;
}
// Default constructor for JSON deserialization
public UniWebViewChannelMessage() { }
///
/// Gets the strongly-typed message type
///
public UniWebViewChannelMessageType MessageType => (UniWebViewChannelMessageType)messageType;
///
/// True if this is a fire-and-forget message (send)
///
public bool isFireAndForget => MessageType == UniWebViewChannelMessageType.Send;
///
/// True if this is a synchronous call (call)
///
public bool isSyncCall => MessageType == UniWebViewChannelMessageType.Call;
///
/// True if this is an asynchronous request (request)
///
public bool isAsyncRequest => MessageType == UniWebViewChannelMessageType.Request;
public bool TryGetData(out T result) {
result = default;
try {
result = UniWebViewJsonUtility.FromJson(data);
return true;
} catch (Exception e) {
UniWebViewLogger.Instance.Critical(() => $"Failed to parse message data for action '{action}': {e.Message}");
return false;
}
}
public T GetData() {
if (TryGetData(out var result)) {
return result;
}
return default(T);
}
// ReSharper disable Unity.PerformanceAnalysis
///
/// Sends an async response for this message
///
/// The response to send back
public void Respond(UniWebViewChannelMessageResponse response) {
if (!isAsyncRequest) {
UniWebViewLogger.Instance.Critical(() => $"Cannot respond to a {MessageType} message. Only Request messages support async responses.");
return;
}
if (_respondDelegate == null) {
UniWebViewLogger.Instance.Critical(() => "Cannot respond: Response delegate is null (message may have been deserialized or webview destroyed)");
return;
}
_respondDelegate(id, response);
}
///
/// Convenience method for success responses
///
/// The data to send back
public void Respond(object data) {
Respond(UniWebViewChannelMessageResponse.Success(data));
}
///
/// Convenience method for error responses
///
/// The error data to send back (supports any JSON-compatible type)
public void RespondError(object errorData) {
Respond(UniWebViewChannelMessageResponse.Error(errorData));
}
}
///
/// Represents a response for a channel message
///
public class UniWebViewChannelMessageResponse {
[Serializable]
class ResultWrapper {
public string result;
}
[Serializable]
class ErrorWrapper {
public string error;
}
///
/// Response data
///
public object data;
///
/// Whether this response represents an error
///
public bool hasError;
///
/// Error data if hasError is true (supports any JSON-compatible type)
///
public object errorData;
///
/// Creates a success response
///
/// The data to include in the response
public UniWebViewChannelMessageResponse(object data) {
this.data = data;
this.hasError = false;
this.errorData = null;
}
///
/// Creates an error response
///
/// The error data (supports any JSON-compatible type)
private UniWebViewChannelMessageResponse(object errorData, bool isError) {
this.data = null;
this.hasError = true;
this.errorData = errorData;
}
internal string ToJson() {
if (hasError) {
return UniWebViewJsonUtility.ToJson(new ErrorWrapper { error = UniWebViewJsonUtility.ToJson(errorData) });
} else {
return UniWebViewJsonUtility.ToJson(new ResultWrapper { result = UniWebViewJsonUtility.ToJson(data) });
}
}
///
/// Static factory method for success responses
///
/// The data to include
/// A success response
public static UniWebViewChannelMessageResponse Success(object data) {
return new UniWebViewChannelMessageResponse(data);
}
///
/// Static factory method for error responses
///
/// The error data (supports any JSON-compatible type)
/// An error response
public static UniWebViewChannelMessageResponse Error(object errorData) {
return new UniWebViewChannelMessageResponse(errorData, true);
}
}