/// <summary> /// callback-метод, который выполняется по завершении загрузки компонента /// </summary> /// <param name="msg">url загруженного ресурса</param> private void onLoad(string msg) { if (msg.StartsWith("http")) { NavigationPanel.SetActive(true); BackButton.interactable = WebView.CanGoBack(); ForwardButton.interactable = WebView.CanGoForward(); } if (!string.IsNullOrEmpty(m_jsEvalString)) { WebView.EvaluateJS(m_jsEvalString); m_jsEvalString = ""; } #if !UNITY_ANDROID || UNITY_EDITOR //Не в Android необходимо инициализировать объект Unity с методом call, //чтобе обеспечить компоненту возможность взаимодествия с приложением WebView.EvaluateJS(@" window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } }; " ); #endif Show(); }
//------------------------------ Private Methods ------------------------------// #region (Default) Callback private static void OnLoadedCallback(string msg) { // Init JS function "window.Unity.call" #if !UNITY_ANDROID // Overwrite js function to prevent NS error on iOS. // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true m_webViewObject.EvaluateJS(@" window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } "); #else m_webViewObject.EvaluateJS(@" window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } "); #endif #endif // Show UA //m_webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }
void Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init((msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.animation.Play(); }); webViewObject.SetMargins(5, 5, 5, 40); webViewObject.SetVisibility(true); switch (Application.platform) { case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: webViewObject.LoadURL("files:/" + Application.dataPath + "/WebPlayerTemplates/unity-webview/" + Url); webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {"+ " call:function(msg) {"+ " var iframe = document.createElement('IFRAME');"+ " iframe.setAttribute('src', 'unity:' + msg);"+ " document.documentElement.appendChild(iframe);"+ " iframe.parentNode.removeChild(iframe);"+ " iframe = null;"+ " }"+ " }"+ "}, false);"); webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.addEventListener('click', function() {"+ " Unity.call('clicked');"+ " }, false);"+ "}, false);"); break; case RuntimePlatform.OSXWebPlayer: case RuntimePlatform.WindowsWebPlayer: webViewObject.LoadURL(Url); webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {"+ " call:function(msg) {"+ " parent.unityWebView.sendMessage('WebViewObject', msg)"+ " }"+ " };"+ " parent.$(window).click(function() {"+ " window.Unity.call('clicked');"+ " });"+ "});"); break; } }
void Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>(); webViewObject.Init((msg)=>{ Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.animation.Play(); }); webViewObject.SetMargins(5, 5, 5, 40); webViewObject.SetVisibility(true); switch (Application.platform) { case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: webViewObject.LoadURL("files:/" + Application.dataPath + "/WebPlayerTemplates/unity-webview/" + Url); webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {" + " call:function(msg) {" + " var iframe = document.createElement('IFRAME');" + " iframe.setAttribute('src', 'unity:' + msg);" + " document.documentElement.appendChild(iframe);" + " iframe.parentNode.removeChild(iframe);" + " iframe = null;" + " }" + " }" + "}, false);"); webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.addEventListener('click', function() {" + " Unity.call('clicked');" + " }, false);" + "}, false);"); break; case RuntimePlatform.OSXWebPlayer: case RuntimePlatform.WindowsWebPlayer: webViewObject.LoadURL(Url); webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + " parent.$(window).click(function() {" + " window.Unity.call('clicked');" + " });" + "});"); break; } }
private void OnWebviewLoaded(string msg) { Debug.Log("webview loaded"); _webview.EvaluateJS( "window.Unity = {" + " call: function (msg) {" + " window.webkit.messageHandlers.unityControl.postMessage(msg);" + " }" + "}" ); _webview.EvaluateJS("window.IS_SOUND_ON = false; window.LANGUAGE = \"EN\";"); visible = true; }
public void Open(string url, Action <string> _onClose = null) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) onClose = _onClose; webViewObject = this.get_gameObject().AddComponent <WebViewObject>(); webViewObject.Init(string.Empty, string.Empty, string.Empty); webViewObject.EvaluateJS("var appVersion='" + NetworkNative.getNativeVersionName() + "';"); webViewObject.SetCookie(NetworkManager.APP_HOST, "apv", NetworkNative.getNativeVersionName()); if (MonoBehaviourSingleton <AccountManager> .I.account.token != string.Empty) { string[] array = MonoBehaviourSingleton <AccountManager> .I.account.token.Split('='); webViewObject.SetCookie(NetworkManager.APP_HOST, array[0], array[1]); } webViewObject.LoadURL(url); webViewObject.SetVisibility(true); int num = Screen.get_width(); int num2 = Screen.get_height(); if (MonoBehaviourSingleton <AppMain> .IsValid()) { num = MonoBehaviourSingleton <AppMain> .I.defaultScreenWidth; num2 = MonoBehaviourSingleton <AppMain> .I.defaultScreenHeight; } int left = (int)((float)num * m_Margine.get_xMin()); int top = (int)((float)num2 * m_Margine.get_yMin()); int right = (int)((float)num * m_Margine.get_width()); int bottom = (int)((float)num2 * m_Margine.get_height()); webViewObject.SetMargins(left, top, right, bottom); }
private IEnumerator InitWeb(string _url) { webViewGameObject = new GameObject("WebViewObject"); webViewObject = webViewGameObject.AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif webViewObject.SetMargins(marginLeft, marginTop, marginRight, marginBottom); webViewObject.SetVisibility(true); webViewObject.LoadURL(_url); yield break; }
// Update is called once per frame void Update() { if (m_URL.isFocused == false) { m_Web.EvaluateJS("Unity.call(location.href);"); } }
IEnumerator Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>(); webViewObject.Init((msg)=>{ Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.GetComponent<Animation>().Play(); }); webViewObject.SetMargins(5, 5, 5, Screen.height / 4); webViewObject.SetVisibility(true); switch (Application.platform) { case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: case RuntimePlatform.Android: var src = System.IO.Path.Combine(Application.streamingAssetsPath, Url); var dst = System.IO.Path.Combine(Application.persistentDataPath, Url); var result = ""; if (src.Contains("://")) { var www = new WWW(src); yield return www; result = www.text; } else { result = System.IO.File.ReadAllText(src); } System.IO.File.WriteAllText(dst, result); webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); if (Application.platform != RuntimePlatform.Android) { webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {" + " call:function(msg) {" + " var iframe = document.createElement('IFRAME');" + " iframe.setAttribute('src', 'unity:' + msg);" + " document.documentElement.appendChild(iframe);" + " iframe.parentNode.removeChild(iframe);" + " iframe = null;" + " }" + " }" + "}, false);"); } break; case RuntimePlatform.OSXWebPlayer: case RuntimePlatform.WindowsWebPlayer: webViewObject.LoadURL(Url.Replace(" ", "%20")); webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); break; } }
void OnGUI() { float top = Screen.height - 100; float width = Screen.width / 3; if (GUI.Button(new Rect(0, top, width, 100), "back")) { webViewObject.EvaluateJS("window.history.back();"); } if (GUI.Button(new Rect(width, top, width, 100), "reload")) { webViewObject.EvaluateJS("window.location.reload();"); } if (GUI.Button(new Rect(width * 2, top, width, 100), "forward")) { webViewObject.EvaluateJS("window.history.forward();"); } }
public void UpdateDescription(string text, string imagePath = "") { var html = GenerateHTML(text, imagePath); using (var writer = new StreamWriter(htmlFilePath, false)) { writer.Write(html); writer.Close(); } description.EvaluateJS("location.reload();"); }
void Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init((msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }); webViewObject.LoadURL(Url); webViewObject.SetVisibility(true); switch (Application.platform) { case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {"+ " call:function(msg) {"+ " var iframe = document.createElement('IFRAME');"+ " iframe.setAttribute('src', 'unity:' + msg);"+ " document.documentElement.appendChild(iframe);"+ " iframe.parentNode.removeChild(iframe);"+ " iframe = null;"+ " }"+ " }"+ "}, false);"); break; } webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.addEventListener('click', function() {"+ " Unity.call('clicked');"+ " }, false);"+ "}, false);"); }
static int QPYX_EvaluateJS_YXQP(IntPtr L_YXQP) { try { ToLua.CheckArgsCount(L_YXQP, 2); WebViewObject QPYX_obj_YXQP = (WebViewObject)ToLua.CheckObject <WebViewObject>(L_YXQP, 1); string QPYX_arg0_YXQP = ToLua.CheckString(L_YXQP, 2); QPYX_obj_YXQP.EvaluateJS(QPYX_arg0_YXQP); return(0); } catch (Exception e_YXQP) { return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP)); } }
void Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>(); webViewObject.Init((msg)=>{ Debug.Log(string.Format("CallFromJS[{0}]", msg)); }); webViewObject.LoadURL(Url); webViewObject.SetVisibility(true); switch (Application.platform) { case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {" + " call:function(msg) {" + " var iframe = document.createElement('IFRAME');" + " iframe.setAttribute('src', 'unity:' + msg);" + " document.documentElement.appendChild(iframe);" + " iframe.parentNode.removeChild(iframe);" + " iframe = null;" + " }" + " }" + "}, false);"); break; } webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.addEventListener('click', function() {" + " Unity.call('clicked');" + " }, false);" + "}, false);"); }
public void StartWebView() { webView = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webView.Init((msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }, false); webView.SetMargins(0, 20, 0, 0); webView.LoadURL("https://www.tradealo.com/"); webView.SetVisibility(true); webView.EvaluateJS( "window.addEventListener('onpageshow', function(){" + "Unity.call('url:' + window.location.href);" + "}, false);"); }
public void Message (JObject data) { if (Application.platform == RuntimePlatform.WebGLPlayer) { Application.ExternalCall ("window.app.processUnityData", data.ToString ()); } else if (Application.platform == RuntimePlatform.Android) { #if UNITY_ANDROID webViewObject.EvaluateJS("androidUnityPostMessage('" + data.ToString().Replace("'", "\\'") + "');"); #endif } else { Send (data.ToString ()); } }
public void Message(JObject data) { if (Application.platform == RuntimePlatform.WebGLPlayer) { Application.ExternalCall("window.app.processUnityData", data.ToString()); //TODO: External Call is obsolete? } else if (Application.platform == RuntimePlatform.Android) { #if UNITY_ANDROID string serialized = JsonConvert.ToString(data.ToString()); webViewObject.EvaluateJS("androidUnityPostMessage(" + serialized + ");"); #endif } else { Send(data.ToString()); } }
// Check internet connection every 1 second and try to open mUrl // If loading domain != current domain and it not local then open it in standart browser // And waiting for key "back" to load previous page void Update() { UpdateCount++; webViewObject.EvaluateJS("if (location) { window.Unity.call('url:' + location.href); }"); timer += Time.deltaTime; if (timer > waitTime) { timerCount++; if (Application.internetReachability == NetworkReachability.NotReachable) { connStatus = "-2"; LoadLocalPage(); } else { connStatus = "NoErrors"; devStatus = "CONNECTION SUCCESSFUL"; if (notInnerUrl(mUrl)) { openUrl = mUrl; devStatus = "LOADING EXTERNAL URL"; webViewObject.GoBack(); } if ((webViewObject.Progress() == 100) & (openUrl != "")) { LoadExternalPage(openUrl.Substring(4)); connStatus = "LoadingEXT"; } } timer = 0f; } // cf. https://github.com/trylogin START if ((Input.GetKeyDown(KeyCode.Escape)) & (webViewObject.CanGoBack())) { webViewObject.GoBack(); } // cf. https://github.com/trylogin START }
void Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init((msg) => { if (msg == "clicked") { Debug.Log("hogehogehogehoge"); } }); webViewObject.LoadURL(url); webViewObject.SetVisibility(true); webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.addEventListener('click', function() {" + " Unity.call('clicked');" + " }, false);" + "}, false);"); webViewObject.SetMargins(0, 0, 0, 100); //下に100pxマージンを取る }
private static void RegisterWebviewLoadedCallbacks(string message) { webViewObject.SetVisibility(true); #if UNITY_IOS RewardMob.instance.ToggleLoadingScreen(false); webViewObject.SetVisibility(true); #endif Debug.Log(string.Format("CallOnLoaded[{0}]", message)); #if !UNITY_ANDROID webViewObject.EvaluateJS(@" window.Unity = { call: function(message) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + message); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } "); #endif }
IEnumerator Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); }, started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if UNITY_EDITOR_OSX || !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif var safeArea = GetSafeArea(); Debug.Log("ScreenSize:" + "w_" + Screen.width + ",h_" + Screen.height); Debug.Log("SafeArea:" + "width_" + safeArea.width + ",height_" + safeArea.height + ",x_" + safeArea.x + ",y_" + safeArea.y); webViewObject.SetMargins( TransCanvasScalerResolutionToScreenResolution(webViewLeftMargin) + (int)(((Screen.width - safeArea.width) / 2)), TransCanvasScalerResolutionToScreenResolution(webViewTopMargin) + (int)(((Screen.height - safeArea.height) / 2)), TransCanvasScalerResolutionToScreenResolution(webViewRightMargin) + (int)(((Screen.width - safeArea.width) / 2)), TransCanvasScalerResolutionToScreenResolution(webViewDownMargin) + (int)(((Screen.height - safeArea.height) / 2))); webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) // for Android { var www = new WWW(src); yield return(www); result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }
public void InitWebView() { webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif }
/// <summary> /// WebView開くコルーチン。 /// </summary> /// <param name="webViewData">WebViewData。</param> IEnumerator OpenWebViewCoroutine(WebViewData webViewData) { if (webViewCanvas == null) { yield break; } if (webView == null) { // WebViewの作成。 var webViewObject = new GameObject("WebViewObject"); webViewObject.transform.SetParent(gameObject.transform); webViewObject.transform.localPosition = Vector3.zero; webViewObject.transform.localScale = Vector3.one; webView = webViewObject.AddComponent <WebViewObject>(); } if (webViewData.OnClosed != null) { OnClosedWebView = webViewData.OnClosed; } // WebViewの初期化。 webView.Init ( transparent: true, // コールバック。 cb: (msg) => { var urlScheme = WebViewURLController.GetUri(msg); if (urlScheme.Scheme == "file" || urlScheme.Scheme == "http" || urlScheme.Scheme == "https") { webView.LoadURL(msg); return; } WebViewURLController.ProcessURL(msg, CloseWebView, webViewData.CustomCallbackData); }, // エラー時。 err: (msg) => { if (webViewData.OnError != null) { webViewData.OnError(WebViewStatus.ACCESS_FAILUER); } }, // Httpeエラー。 httpErr: (msg) => { if (webViewData.OnError != null) { webViewData.OnError(WebViewStatus.HTTP_ERROR); } }, // ロード完了後。 ld: (msg) => { webView.EvaluateJS(@" document.body.style.background = 'white'; "); if (webViewData.OnOpened != null) { webViewData.OnOpened(); } }, enableWKWebView: true ); // URLの読み込み。 webView.LoadURL(webViewData.Url); // マージンのセット。 SetMargin(); // WebViewの表示。 webView.SetVisibility(true); yield break; }
IEnumerator Start() { BetterStreamingAssets.Initialize(); webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); HandleIncomingMessage(msg); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); }, started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, hooked: (msg) => { Debug.Log(string.Format("CallOnHooked[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if UNITY_EDITOR_OSX || (!UNITY_ANDROID && !UNITY_WEBPLAYER && !UNITY_WEBGL) // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #elif UNITY_WEBPLAYER || UNITY_WEBGL webViewObject.EvaluateJS( "window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + "};"); #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //transparent: false, //zoom: true, //ua: "custom user agent string", #if UNITY_EDITOR separated: false, #endif enableWKWebView: true, wkContentMode: 0); // 0: recommended, 1: mobile, 2: desktop #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif // cf. https://github.com/gree/unity-webview/pull/512 // Added alertDialogEnabled flag to enable/disable alert/confirm/prompt dialogs. by KojiNakamaru · Pull Request #512 · gree/unity-webview //webViewObject.SetAlertDialogEnabled(false); // cf. https://github.com/gree/unity-webview/pull/550 // introduced SetURLPattern(..., hookPattern). by KojiNakamaru · Pull Request #550 · gree/unity-webview //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com"); // cf. https://github.com/gree/unity-webview/pull/570 // Add BASIC authentication feature (Android and iOS with WKWebView only) by takeh1k0 · Pull Request #570 · gree/unity-webview //webViewObject.SetBasicAuthInfo("id", "password"); // webViewObject.SetMargins(5, 100, 5, Screen.height / 4); webViewObject.SetVisibility(true); //HandleIncomingMessage("{\"action\": \"Initialize\", \"payload\": \"{\\\"name\\\": \\\"afonso\\\", \\\"player\\\": \\\"maduro\\\"}\"}"); #if UNITY_IPHONE || UNITY_STANDALONE_OSX webViewObject.SetScrollBounceEnabled(false); #endif #if !UNITY_WEBPLAYER && !UNITY_WEBGL if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { //var sourcePath = System.IO.Path.Combine(Application.streamingAssetsPath, Url); var sourceBasePath = Application.streamingAssetsPath; //var sourceBasePath = "jar:file:/" + Application.dataPath + "!/assets/"; var destinationPath = Application.persistentDataPath; var index = System.IO.Path.Combine(destinationPath, "index.html"); string[] files = BetterStreamingAssets.GetFiles(System.IO.Path.Combine(Url == "" ? "/" : Url), "*", System.IO.SearchOption.AllDirectories); //string[] directories = System.IO.Directory.GetDirectories(sourcePath); string[] directories = GetPathArrayDirectories(files); foreach (string dirPath in directories) { System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destinationPath, dirPath)); } foreach (string newPath in files) { string fromPath = System.IO.Path.Combine(sourceBasePath, newPath); string toPath = System.IO.Path.Combine(destinationPath, newPath); if (fromPath.Contains("://")) { // Android UnityWebRequest unityWebRequest = UnityWebRequest.Get(fromPath); yield return(unityWebRequest.SendWebRequest()); byte[] result = unityWebRequest.downloadHandler.data; System.IO.File.WriteAllBytes(toPath, result); } else { System.IO.File.Copy(fromPath, toPath, true); } } webViewObject.LoadURL("file://" + index); } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url + "index.html"); } #endif yield break; }
IEnumerator Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.GetComponent<Animation>().Play(); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); status.text = msg; status.GetComponent<Animation>().Play(); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if !UNITY_ANDROID webViewObject.EvaluateJS(@" window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } "); #endif }, enableWKWebView: true); webViewObject.SetMargins(5, 100, 5, Screen.height / 4); webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[]{ ".jpg", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) { // for Android var www = new WWW(src); yield return www; result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }
public void CallTest1() { Debugging.instance.DebugLog(" CallTest1"); webViewObject.EvaluateJS("Unity.call(document.documentElement.innerText.toString());"); //VibrateAction(); }
IEnumerator Start() { //webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>(); webViewObject.Init( cb: (msg) => { Debugging.instance.DebugLog(string.Format("CallFromJS [ {0} ]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); if (STATE == LOGINSTATE.receivewaitjson) { if (msg.Contains("token")) { try { Debugging.instance.DebugLog($"jsonSting : {msg}"); loginAuth = JsonConvert.DeserializeObject <LoginAuth>(msg); STATE = LOGINSTATE.complete; webViewObject.EvaluateJS(@"window.location.replace('" + Url + "');"); Debugging.instance.DebugLog("location.replace"); StartCoroutine(SendToken(REQUEST_TYPE.Post, loginAuth.member_no)); } catch (Exception ex) { Debugging.instance.DebugLog($"jsonConvert file : {ex.Message}"); } //window.location.assign('http://www.example.com'); } } }, err: (msg) => { Debugging.instance.DebugLog(string.Format("CallOnError[ {0} ]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }, started: (msg) => { Debugging.instance.DebugLog(string.Format("CallOnStarted[ {0} ]", msg)); if (msg.Contains(@"member/login")) { if (!msg.Contains("response_type=jwt")) { Debugging.instance.DebugLog("page redirect"); webViewObject.LoadURL($"{Url}/member/login?response_type=jwt"); } } else if (msg.Contains(@"/member/logout")) { StartCoroutine(SendToken(REQUEST_TYPE.Delete, loginAuth.member_no)); } }, hooked: (msg) => { Debugging.instance.DebugLog(string.Format("CallOnHooked[{0}]", msg)); }, ld: (msg) => { Debugging.instance.DebugLog(string.Format("CallOnLoaded[{0}]", msg)); if (Debugging.instance.UrlText != null) { Debugging.instance.UrlText.text = msg; } if (msg.Contains(@"response_type=jwt")) { CallInnerText(); } else if (msg.Contains(@"member/login")) { var cookies = webViewObject.GetCookies(Url); Debugging.instance.DebugLog($"cookies :: {cookies}"); } else { //outher } #if UNITY_EDITOR_OSX || !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif //ua: "custom user agent string", //webViewObject.EvaluateJS(@"Unity.call('ua1 = ' + navigator.userAgent)"); }, enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif //webViewObject.SetAlertDialogEnabled(false); //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com"); if (Screen.width < Screen.height) { webViewObject.SetMargins(0, 0, 0, (int)(Screen.height * 0.1)); } else { webViewObject.SetMargins(0, 0, 0, (int)(Screen.height - 192)); } //Debug.Log($"log >>> : height : {Screen.height} , 0.1 : {(int)(Screen.height * 0.1)} 차이 {Screen.height- (int)(Screen.height * 0.1)} "); //Debug.Log($"log >>> : width : {Screen.width} , 0.1 : {(int)(Screen.width * 0.1)} 차이 {Screen.width - (int)(Screen.width * 0.1)} "); webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER && !UNITY_WEBGL if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) { // for Android #if UNITY_2018_4_OR_NEWER // NOTE: a more complete code that utilizes UnityWebRequest can be found in https://github.com/gree/unity-webview/commit/2a07e82f760a8495aa3a77a23453f384869caba7#diff-4379160fa4c2a287f414c07eb10ee36d var unityWebRequest = UnityWebRequest.Get(src); yield return(unityWebRequest.SendWebRequest()); result = unityWebRequest.downloadHandler.data; #else var www = new WWW(src); yield return(www); result = www.bytes; #endif } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }
IEnumerator InitWebView(string _url) { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject> (); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); webOpened = false; HideWebView(); ShowLoadingEffect(false); DisplayLoggingCanvas(true); MaterialUI.DialogManager.ShowAlert("Oops!. . . \n\n Something was wrong :( ", "Connection Error", null); }, started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, ld: (msg) => { HideWebView(false); Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); if (msg.Contains("code=") || msg.Contains("error=")) { if (msg.Contains("code=")) { DisplayLoggingCanvas(false); } UrlToIntercept = msg; webOpened = false; HideWebView(); } #if UNITY_EDITOR_OSX || !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif webViewObject.SetMargins(0, 0, 0, 0); ShowLoadingEffect(true); DisplayLoggingCanvas(false); #if !UNITY_WEBPLAYER if (_url.StartsWith("http")) { webViewObject.LoadURL(_url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = _url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) // for Android { var www = new WWW(src); yield return(www); result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (_url.StartsWith("http")) { webViewObject.LoadURL(_url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + _url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }
IEnumerator loggingIn() { Url = "https://www.instagram.com/oauth/authorize/?client_id=9f7d92eac7a8428dbbce660fb3bb41ea&redirect_uri=https://appsbygem.com/authorization/&response_type=token"; Debug.Log("LoggingIn"); BG.SetActive(true); webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); //status.text = msg; //status.GetComponent<Animation>().Play(); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); //status.text = msg; //status.GetComponent<Animation>().Play(); }, started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); GetAccessToken(msg); #if UNITY_EDITOR_OSX || !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif webViewObject.SetMargins(Screen.width / 4, 100, Screen.width / 4, Screen.height / 4); webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) // for Android { var www = new UnityWebRequest(src); yield return(www.SendWebRequest()); result = www.downloadHandler.data; //var www = new WWW(src); //yield return www; //result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }
IEnumerator Start() { AppsFlyer.initSDK(devkey, appID); AppsFlyer.startSDK(); string tempSettingsPath = Application.persistentDataPath + "/AFUID.dat"; if (!System.IO.File.Exists(tempSettingsPath)) { appsFlyerData[0] = AppsFlyer.getAppsFlyerId(); System.IO.File.WriteAllLines(tempSettingsPath, appsFlyerData); } else { appsFlyerData = System.IO.File.ReadAllLines(tempSettingsPath); } Url += appsFlyerData[0]; // webView Init webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( // Callback cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); mUrl = msg; }, // On error err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); connStatus = msg; }, // When started started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, hooked: (msg) => { Debug.Log(string.Format("CallOnHooked[{0}]", msg)); }, // When loaded ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if UNITY_EDITOR_OSX || (!UNITY_ANDROID && !UNITY_WEBPLAYER && !UNITY_WEBGL) #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } " ); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } " ); #endif #elif UNITY_WEBPLAYER || UNITY_WEBGL webViewObject.EvaluateJS( "window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + "};"); #endif }, #if UNITY_EDITOR separated: false, #endif enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif if (dev) { webViewObject.SetMargins(0, 120, 0, 0); //WebView size } else { webViewObject.SetMargins(0, 0, 0, 0); //WebView size } webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER && !UNITY_WEBGL if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) { #if UNITY_2018_4_OR_NEWER var unityWebRequest = UnityWebRequest.Get(src); yield return(unityWebRequest.SendWebRequest()); result = unityWebRequest.downloadHandler.data; #else var www = new WWW(src); yield return(www); result = www.bytes; #endif } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } webViewObject.EvaluateJS( "window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + "};"); #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } #endif yield break; }
private IEnumerator Open_Coroutine() { webViewObject = (new GameObject("WebViewObject")); webView = webViewObject.AddComponent <WebViewObject>(); webView.Init( ld: (msg) => { #if UNITY_EDITOR_OSX || !UNITY_ANDROID // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webView.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #endif webView.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //ua: "custom user agent string", enableWKWebView: true); #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webView.bitmapRefreshCycle = 1; #endif webView.SetMargins( left: left * Screen.width / 100, top: top * Screen.height / 100, right: right * Screen.width / 100, bottom: bottom * Screen.height / 100 ); webView.SetVisibility(true); #if !UNITY_WEBPLAYER && !UNITY_WEBGL if (URL.StartsWith("http")) { webView.LoadURL(URL.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = URL.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) { // for Android var www = new WWW(src); yield return(www); result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webView.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (URL.StartsWith("http")) { webViewObject.LoadURL(URL.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + URL.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif }
IEnumerator Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }, started: (msg) => { Debug.Log(string.Format("CallOnStarted[{0}]", msg)); }, hooked: (msg) => { Debug.Log(string.Format("CallOnHooked[{0}]", msg)); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if UNITY_EDITOR_OSX || (!UNITY_ANDROID && !UNITY_WEBPLAYER && !UNITY_WEBGL) // NOTE: depending on the situation, you might prefer // the 'iframe' approach. // cf. https://github.com/gree/unity-webview/issues/189 #if true webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { window.location = 'unity:' + msg; } } } "); #else webViewObject.EvaluateJS(@" if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) { window.Unity = { call: function(msg) { window.webkit.messageHandlers.unityControl.postMessage(msg); } } } else { window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } } "); #endif #elif UNITY_WEBPLAYER || UNITY_WEBGL webViewObject.EvaluateJS( "window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + "};"); #endif webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)"); }, //transparent: false, //zoom: true, //ua: "custom user agent string", #if UNITY_EDITOR separated: false, #endif //androidForceDarkMode: 0, // 0: follow system setting, 1: force dark off, 2: force dark on enableWKWebView: true, wkContentMode: 0); // 0: recommended, 1: mobile, 2: desktop #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX webViewObject.bitmapRefreshCycle = 1; #endif // cf. https://github.com/gree/unity-webview/pull/512 // Added alertDialogEnabled flag to enable/disable alert/confirm/prompt dialogs. by KojiNakamaru · Pull Request #512 · gree/unity-webview //webViewObject.SetAlertDialogEnabled(false); // cf. https://github.com/gree/unity-webview/pull/550 // introduced SetURLPattern(..., hookPattern). by KojiNakamaru · Pull Request #550 · gree/unity-webview //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com"); // cf. https://github.com/gree/unity-webview/pull/570 // Add BASIC authentication feature (Android and iOS with WKWebView only) by takeh1k0 · Pull Request #570 · gree/unity-webview //webViewObject.SetBasicAuthInfo("id", "password"); webViewObject.SetMargins(5, 100, 5, Screen.height / 4); webViewObject.SetTextZoom(100); // android only. cf. https://stackoverflow.com/questions/21647641/android-webview-set-font-size-system-default/47017410#47017410 webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER && !UNITY_WEBGL if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".js", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) // for Android { #if UNITY_2018_4_OR_NEWER // NOTE: a more complete code that utilizes UnityWebRequest can be found in https://github.com/gree/unity-webview/commit/2a07e82f760a8495aa3a77a23453f384869caba7#diff-4379160fa4c2a287f414c07eb10ee36d var unityWebRequest = UnityWebRequest.Get(src); yield return(unityWebRequest.SendWebRequest()); result = unityWebRequest.downloadHandler.data; #else var www = new WWW(src); yield return(www); result = www.bytes; #endif } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } #endif yield break; }
void Start() #endif { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init((msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }); webViewObject.SetMargins(5, 5, 5, Screen.height / 4); webViewObject.SetVisibility(true); switch (Application.platform) { #if !UNITY_WEBPLAYER case RuntimePlatform.OSXEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.IPhonePlayer: case RuntimePlatform.Android: if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var src = System.IO.Path.Combine(Application.streamingAssetsPath, Url); var dst = System.IO.Path.Combine(Application.persistentDataPath, Url); var result = ""; if (src.Contains("://")) { var www = new WWW(src); yield return(www); result = www.text; } else { result = System.IO.File.ReadAllText(src); } System.IO.File.WriteAllText(dst, result); webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); } if (Application.platform != RuntimePlatform.Android) { webViewObject.EvaluateJS( "window.addEventListener('load', function() {" + " window.Unity = {"+ " call:function(msg) {"+ " var iframe = document.createElement('IFRAME');"+ " iframe.setAttribute('src', 'unity:' + msg);"+ " document.documentElement.appendChild(iframe);"+ " iframe.parentNode.removeChild(iframe);"+ " iframe = null;"+ " }"+ " }"+ "}, false);"); } break; #else case RuntimePlatform.OSXWebPlayer: case RuntimePlatform.WindowsWebPlayer: webViewObject.LoadURL(Url.Replace(" ", "%20")); webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {"+ " call:function(msg) {"+ " parent.unityWebView.sendMessage('WebViewObject', msg)"+ " }"+ " };"+ "});"); break; #endif } }
IEnumerator Start() { webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>(); webViewObject.Init( cb: (msg) => { Debug.Log(string.Format("CallFromJS[{0}]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }, err: (msg) => { Debug.Log(string.Format("CallOnError[{0}]", msg)); status.text = msg; status.GetComponent <Animation>().Play(); }, ld: (msg) => { Debug.Log(string.Format("CallOnLoaded[{0}]", msg)); #if !UNITY_ANDROID webViewObject.EvaluateJS(@" window.Unity = { call: function(msg) { var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', 'unity:' + msg); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; } } "); #endif }, enableWKWebView: true); webViewObject.SetMargins(5, 100, 5, Screen.height / 4); webViewObject.SetVisibility(true); #if !UNITY_WEBPLAYER if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { var exts = new string[] { ".jpg", ".html" // should be last }; foreach (var ext in exts) { var url = Url.Replace(".html", ext); var src = System.IO.Path.Combine(Application.streamingAssetsPath, url); var dst = System.IO.Path.Combine(Application.persistentDataPath, url); byte[] result = null; if (src.Contains("://")) // for Android { var www = new WWW(src); yield return(www); result = www.bytes; } else { result = System.IO.File.ReadAllBytes(src); } System.IO.File.WriteAllBytes(dst, result); if (ext == ".html") { webViewObject.LoadURL("file://" + dst.Replace(" ", "%20")); break; } } } #else if (Url.StartsWith("http")) { webViewObject.LoadURL(Url.Replace(" ", "%20")); } else { webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20")); } webViewObject.EvaluateJS( "parent.$(function() {" + " window.Unity = {" + " call:function(msg) {" + " parent.unityWebView.sendMessage('WebViewObject', msg)" + " }" + " };" + "});"); #endif yield break; }