124 lines
3.2 KiB
C#
124 lines
3.2 KiB
C#
using Gree.UnityWebView;
|
|
using UnityEngine;
|
|
|
|
public class FreeWebViewManager : MonoBehaviour
|
|
{
|
|
public static FreeWebViewManager Instance;
|
|
private GameObject _webObj;
|
|
private WebViewObject1 _webView;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance != null) Destroy(gameObject);
|
|
else
|
|
{
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
initView();
|
|
}
|
|
|
|
public void initView()
|
|
{
|
|
// if (_webObj != null) return;
|
|
//
|
|
// // 创建WebView对象
|
|
// _webObj = new GameObject("WebViewObject1");
|
|
// _webView = _webObj.AddComponent<WebViewObject1>();
|
|
//
|
|
// // 关键:开启WKWebView,规避苹果审核拒绝
|
|
// _webView.Init(
|
|
// enableWKWebView: true,
|
|
// cb: OnWebMessage // JS调用Unity回调
|
|
// );
|
|
//
|
|
// float top_offset = 0;//fgui中的顶部信息的高度
|
|
// float buttom_offset = 155;
|
|
// if (Screen.safeArea.y != 0)
|
|
// {//刘海屏
|
|
// top_offset += Screen.safeArea.y;
|
|
// }
|
|
//
|
|
// // 铺满屏幕,适配刘海安全区
|
|
// _webView.SetMargins(0, (int)top_offset, 0, (int)buttom_offset);
|
|
// // 禁止下拉回弹(可选)
|
|
// _webView.SetScrollBounceEnabled(false);
|
|
//
|
|
// _webView.LoadURL("about:blank");
|
|
// _webView.SetVisibility(false);
|
|
//
|
|
}
|
|
|
|
/// <summary>
|
|
/// 打开网页
|
|
/// </summary>
|
|
public void OpenWeb(string url)
|
|
{
|
|
if (_webObj != null) return;
|
|
|
|
// 创建WebView对象
|
|
_webObj = new GameObject("WebViewObject1");
|
|
_webView = _webObj.AddComponent<WebViewObject1>();
|
|
|
|
// 关键:开启WKWebView,规避苹果审核拒绝
|
|
_webView.Init(
|
|
enableWKWebView: true,
|
|
cb: OnWebMessage // JS调用Unity回调
|
|
);
|
|
|
|
float top_offset = 0;//fgui中的顶部信息的高度
|
|
float buttom_offset = 155;
|
|
if (Screen.safeArea.y != 0)
|
|
{//刘海屏
|
|
top_offset += Screen.safeArea.y;
|
|
}
|
|
|
|
// 铺满屏幕,适配刘海安全区
|
|
_webView.SetMargins(0, (int)top_offset, 0, (int)buttom_offset);
|
|
// 禁止下拉回弹(可选)
|
|
_webView.SetScrollBounceEnabled(false);
|
|
|
|
// 加载网页并显示
|
|
_webView.LoadURL(url);
|
|
_webView.SetVisibility(true);
|
|
}
|
|
|
|
// JS向Unity发消息:window.unity.call("func","参数")
|
|
void OnWebMessage(string msg)
|
|
{
|
|
Debug.Log("收到网页消息:" + msg);
|
|
}
|
|
|
|
// C#调用网页JS
|
|
public void CallJs(string jsCode)
|
|
{
|
|
if (_webView != null)
|
|
_webView.EvaluateJS(jsCode);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 关闭网页(必调用,释放原生资源)
|
|
/// </summary>
|
|
public void CloseWeb()
|
|
{
|
|
if (_webObj != null)
|
|
{
|
|
OnDestroy();
|
|
}
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (_webObj != null)
|
|
{
|
|
_webView.SetVisibility(false);
|
|
Destroy(_webObj);
|
|
_webObj = null;
|
|
_webView = null;
|
|
}
|
|
}
|
|
} |