public static void SetWebView(WebView webView) { webView.NavigationCompleted += async(view, args) => { App.currentMainPage.HideLoading(); await InsertCookieAndRefresh(view, args); // if plan to go somewhere, go. Currently include [the reward edit page] // await Utility.ShowMessageDialog("debug: " + isCookieInsertSucceed.ToString(), planToGoUrl); if (isCookieInsertSucceed && planToGoUrl != "") { string url = planToGoUrl; planToGoUrl = ""; App.currentMainPage.ShowLoading("前往 " + url + " ... "); webView.Navigate(new Uri(url)); } }; webView.NewWindowRequested += (sender, args) => { args.Handled = true; WebViewNewWindowRequestedEventArgs argss = args; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, argss.Uri); req.Headers.Referer = argss.Referrer; ((WebView)sender).NavigateWithHttpRequestMessage(req); }; webView.ScriptNotify += (o, args) => { if (args.Value.StartsWith("DATA: ")) { string jsonData = args.Value.Substring(6); StorageManager.SaveAutoCompleteData("", jsonData); //Utility.ShowMessageDialog(o.ToString(), args.Value); } else { Utility.ShowMessageDialog(o.ToString(), args.Value); } }; }
public static void SetWebView(WebView webView, WebView secondWebView) { webView.NavigationCompleted += async(view, args) => { if (App.currentMainPage.isJsDebugConsole) { App.currentMainPage.ShowLoading("🚧 加载调试辅助..."); try { await AddScriptUri(webView, codeLibsMsAppxWeb + "eruda.js"); Debug.WriteLine("## eruda.js loaded."); await Task.Delay(250); await RunJs(webView, "eruda.init()"); await Task.Delay(50); Debug.WriteLine("## eruda.js init."); } catch (Exception) { Debug.WriteLine("## eruda.js failed."); App.currentMainPage.ShowNotify("调试辅助已忽略", "非必须模块,加载不成功", Symbol.Message); } App.currentMainPage.HideLoading(); } if (args.Uri.AbsoluteUri.ToLower().IndexOf("/edit/content") > 0) { App.currentMainPage.isAssistEditorEditing = true; string loadingStatus = "init\n"; try { App.currentMainPage.ShowLoading("加载基础库..."); await AddScriptUri(webView, extensionLibsMsAppxWeb + "react.development.js"); await Task.Delay(50); //unknown reason. ReactDOM is undefined occurs on first start. await AddScriptUri(webView, extensionLibsMsAppxWeb + "react-dom.development.js"); await Task.Delay(200); //unknown reason. ReactDOM is undefined occurs on first start. loadingStatus += "react-done\n"; await AddScriptUri(webView, extensionToolsMsAppxWeb + "AllComps.js"); await AddScriptUri(webView, extensionToolsMsAppxWeb + "AllPoly.js"); loadingStatus += "allpoly-done\n"; //LOADFUNC Config Code if (App.currentMainPage.isCheckedBasicCheck) { Utility.LogEvent("OK_FuncCheckBasicCalled"); App.currentMainPage.ShowLoading("加载基本检查..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "Checker.js"); loadingStatus += "checker-done\n"; } if (App.currentMainPage.isCheckedBigPic) { Utility.LogEvent("OK_FuncBigPicCalled"); App.currentMainPage.ShowLoading("加载大图片框..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "BigPic.js"); loadingStatus += "bigpic-done\n"; } if (App.currentMainPage.isCheckedPicInsert) { Utility.LogEvent("OK_FuncPicInsertCalled"); App.currentMainPage.ShowLoading("加载插入图片..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "PicInsert.js"); loadingStatus += "picinsert-done\n"; } if (App.currentMainPage.isCheckedBriefPic) { Utility.LogEvent("OK_FuncBriefPicCalled"); App.currentMainPage.ShowLoading("加载简介图..."); try { await InjectCommonData(webView); await AddScriptUri(webView, extensionToolsMsAppxWeb + "BriefPic.js"); Utility.LogEvent("YES_BigPicInstSucceed"); loadingStatus += "briefpic-done\n"; } catch (Exception e) { Debug.WriteLine("加载简介图失败: " + e.Message); await Utility.ShowMessageDialog("加载简介图失败", "异常问题,请联系开发者 [email protected]"); } } if (App.currentMainPage.isCheckedAutoComplete) { Utility.LogEvent("OK_FuncAutoCompleteCalled"); App.currentMainPage.ShowLoading("加载自动补全..."); await AddScriptUri(webView, codeLibsMsAppxWeb + "alertify.js"); await AddCssUri(webView, codeLibsMsAppxWeb + "alertify.com.css"); await App.currentMainPage.LoadAutoCompleteAsync(); loadingStatus += "autocomplete-done\n"; } App.currentMainPage.HideLoading(); } catch (Exception e) { App.currentMainPage.ShowNotify("有模块加载失败", e.Message, Symbol.Cancel); await Utility.FireErrorReport("JS模块加载失败", "loadingStatus = " + loadingStatus); } try { await AddScriptUri(webView, "https://cdn.bootcss.com/layer/3.1.0/layer.js"); await AddCssUri(webView, "https://cdn.bootcss.com/layer/3.1.0/theme/default/layer.css?v=3.1.0"); } catch (Exception) { } } else { App.currentMainPage.isAssistEditorEditing = false; } //App.currentMainPage.ShowNotify("到达页面", args.Uri.AbsoluteUri); if (args.Uri.AbsoluteUri.ToLower().StartsWith("http://")) { App.currentMainPage.ShowLoading("当前为HTTP页面,正在跳转到对应HTTPS页面..."); string newUri = args.Uri.AbsoluteUri.Replace("http://", "https://").Replace("HTTP://", "HTTPS://"); webView.Navigate(new Uri(newUri)); return; } App.currentMainPage.HideLoading(); await InsertCookieAndRefresh(view, args); // if plan to go somewhere, go. Currently include [the reward edit page] // await Utility.ShowMessageDialog("debug: " + isCookieInsertSucceed.ToString(), planToGoUrl); if (isCookieInsertSucceed && planToGoUrl != "") { string url = planToGoUrl; planToGoUrl = ""; App.currentMainPage.ShowLoading("前往 " + url + " ... "); webView.Navigate(new Uri(url)); } else { //正常到达的页面,运行自定义功能 await CheckRunNavigateTools(webView, args.Uri.AbsoluteUri); } }; webView.NewWindowRequested += (sender, args) => { args.Handled = true; WebViewNewWindowRequestedEventArgs argss = args; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, argss.Uri); req.Headers.Referer = argss.Referrer; ((WebView)sender).NavigateWithHttpRequestMessage(req); }; webView.NavigationStarting += async(o, args) => { return; //code below have some problems. await RunJs(webView, "window.realCreateElement = false; window.realCreateElementDone = false;"); Debug.WriteLine("# NavigationStarting add DOMContentLoaded handler."); string oldStatus = ""; for (int i = 0; i < 40; i++) { //await RunJs(webView, "window.external.notify('OMG');"); string status = await RunJs(webView, "document.readyState"); Debug.WriteLine("# NavigationStarting document state: " + status); string status2 = await RunJs(webView, "document.createElement.toString()"); Debug.WriteLine("# NavigationStarting document.createElement state: " + status2); if (status != oldStatus) { if (status == "complete") { //await RunJs(webView, "document.addEventListener('DOMContentLoaded', function(event) { window.realCreateElement = window.document.createElement; });"); await RunJs(webView, "window.realCreateElement = window.document.createElement;"); //await RunJs(webView, "window.console.log = () => {return console.warn(...arguments);};"); string result = await RunJs(webView, "window.document.createElement = () => {return window.realCreateElement(...arguments); };"); Debug.WriteLine("# NavigationStarting hacking result: " + result); string status3 = await RunJs(webView, "document.createElement.toString()"); Debug.WriteLine("# NavigationStarting document.createElement state: " + status3); break; } oldStatus = status; } await Task.Delay(20); } }; webView.ScriptNotify += async(o, args) => { if (args.Value.StartsWith("TEST_NOTIFY")) { Debug.WriteLine("# 测试 window.external.notify."); } else if (args.Value.StartsWith("DATA: ")) { string jsonData = args.Value.Substring(6); await StorageManager.SaveAutoCompleteData("", jsonData); //Utility.ShowMessageDialog(o.ToString(), args.Value); } else if (args.Value.StartsWith("ERROR: ")) { await Utility.ShowMessageDialog("javascript 运行异常", args.Value); Utility.LogEvent("ERROR_JSRUN"); await Utility.FireErrorReport("未知的JS运行异常", "latestJsEvaluated=" + latestJsEvaluated, null, args.Value); } else if (args.Value.StartsWith("GOTO: ") || args.Value.StartsWith("2ND-GOTO: ")) { string gotoType = args.Value.Split(':')[0]; string newUri = args.Value.Replace("2ND-GOTO: ", "").Replace("GOTO: ", "").Trim(); string referrer = ""; if (newUri.Contains(" FROM: ")) { string[] us = newUri.Split(new string[] { " FROM: " }, StringSplitOptions.RemoveEmptyEntries); newUri = us[0]; referrer = us[1]; } try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(newUri)); if (referrer != "") { req.Headers.Referer = new Uri(referrer); } if (gotoType == "GOTO") { webView.NavigateWithHttpRequestMessage(req); } else { secondWebView.NavigateWithHttpRequestMessage(req); } App.currentMainPage.ShowNotify("跳转成功", newUri); } catch (Exception ee) { await Utility.ShowMessageDialog("跳转不成功", "尝试跳转目标: " + newUri); await Utility.ShowDetailedError("出错详细信息", ee); } } else if (args.Value.StartsWith("2ND-VISIBILITY: ")) { string val = args.Value.Replace("2ND-VISIBILITY: ", "").Trim(); if (val == "VISIBLE") { App.currentMainPage.ShowNotify("第二页面可见", "可以手动关闭"); App.currentMainPage.SecondWebViewVisibility = true; } else { App.currentMainPage.ShowNotify("第二页面隐藏", "回到主页面"); App.currentMainPage.SecondWebViewVisibility = false; } } else if (args.Value.StartsWith("NOTIFY: ")) { string info = args.Value.Replace("NOTIFY: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 3) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nNOTIFY: 标题 | 说明 | OK/WARN/ERROR "); } Symbol smb = Symbol.Accept; if (nParams[2].Trim() == "WARN") { smb = Symbol.Comment; } if (nParams[2].Trim() == "ERROR") { smb = Symbol.Cancel; } App.currentMainPage.ShowNotify(nParams[0].Trim(), nParams[1].Trim(), smb); } else if (args.Value.StartsWith("LOG-EVENT: ")) { string info = args.Value.Replace("LOG-EVENT: ", ""); Utility.LogEvent(info); } else if (args.Value.StartsWith("SHOW-DIALOG: ")) { string info = args.Value.Replace("SHOW-DIALOG: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 2) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nSHOW-DIALOG: 标题 | 说明"); } await Utility.ShowMessageDialog(nParams[0].Trim(), nParams[1].Trim()); } else if (args.Value.StartsWith("CONFIRM: ")) { string info = args.Value.Replace("CONFIRM: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 2) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nCONFIRM: 标题 | 说明"); } else { bool isConfirmed = await Utility.ShowConfirmDialog(nParams[0].Trim(), nParams[1].Trim()); try { string callee = isConfirmed ? "external_confirmCallbackYes" : "external_confirmCallbackNo"; await WrapInvokeScriptAsync(webView, callee, new string[] { }); } catch (Exception e) { App.currentMainPage.ShowNotify("js调用失败", "external_confirmCallback"); } } } else if (args.Value.StartsWith("LAUNCH: ")) { string url = args.Value.Replace("LAUNCH: ", "").Trim(); await Launcher.LaunchUriAsync(new Uri(url)); App.currentMainPage.ShowNotify("浏览器调用成功", url, Symbol.Accept); } else if (args.Value.StartsWith("SET-DATA: ")) { string data = args.Value.Replace("SET-DATA: ", "").Trim(); JsonObject jo = null; string groupId = ""; try { jo = JsonValue.Parse(data).GetObject(); groupId = jo["group-id"].GetString(); } catch (Exception e) { Utility.LogEvent("NO_CommonDataParseError"); await Utility.ShowMessageDialog("保存数据调用格式错误", "请确定是JSON字符串,且含有字符串成员 group-id"); await Utility.ShowDetailedError("详细错误信息", e); return; } StorageManager.SetCommonData(groupId, jo); await StorageManager.SaveCommonData(groupId); Utility.LogEvent("YES_CommonDataSucceed"); App.currentMainPage.ShowNotify("数据保存成功", "保存组别为" + groupId); } else if (args.Value.StartsWith("SAVE-PIC: ") || args.Value.StartsWith("SAVEAS-PIC: ") || args.Value.StartsWith("GET-PIC-FOR-UPLOAD: ")) { bool isSave = args.Value.StartsWith("SAVE-PIC: "); bool isSaveAs = args.Value.StartsWith("SAVEAS-PIC: "); bool isGetPic = args.Value.StartsWith("GET-PIC-FOR-UPLOAD: "); string[] data = args.Value.Replace("SAVEAS-PIC: ", "").Replace("SAVE-PIC: ", "").Replace("GET-PIC-FOR-UPLOAD: ", "").Trim().Split('|'); if (data.Length != 3) { await Utility.ShowMessageDialog("保存图片调用格式不正确", "正确格式为 SAVEAS-PIC/SAVE-PIC/GET-PIC-FOR-UPLOAD: : 宽高比 | 宽度 | 高度"); return; } else { App.currentMainPage.ShowLoading("保存简介图..."); double ratio = 1; int width = 100; int height = 100; WriteableBitmap img = null; try { ratio = Convert.ToDouble(data[0].Trim()); width = Convert.ToInt32(data[1].Trim()); height = Convert.ToInt32(data[2].Trim()); img = await App.currentMainPage.GetWebViewImageAsync(ratio, width, height); } catch (Exception e) { await Utility.ShowMessageDialog("图片生成失败", e.Message); } if (img != null) { if (isGetPic) { try { string base64 = await Utility.WritableBitmapToPngBase64Async(img); await WrapInvokeScriptAsync( webView, "external_getUploadPicSucceed", new string[] { base64 }); App.currentMainPage.HideLoading(); } catch (Exception e) { await Utility.ShowMessageDialog("图片转码和发送失败", e.Message); App.currentMainPage.HideLoading(); try { await WrapInvokeScriptAsync( webView, "external_getUploadPicFailed", new string[] { e.Message }); } catch (Exception) { } } } else { try { bool isSaved = await StorageManager.SaveWritableBitmapAsync(img, isSaveAs); App.currentMainPage.HideLoading(); if (!isSaved) { App.currentMainPage.ShowNotify("取消保存", "简介图未保存", Symbol.Cancel); } } catch (Exception e) { await Utility.ShowMessageDialog("保存简介图片失败", "未能保存到文件"); await Utility.ShowDetailedError("错误详细信息", e); App.currentMainPage.HideLoading(); return; } } } } } else if (args.Value.StartsWith("IMAGE-GET: ")) { string originalUrl = args.Value.Replace("IMAGE-GET: ", "").Trim(); Debug.WriteLine("## IMAGE-GET: " + originalUrl); try { string url = originalUrl; bool isCaching = true; if (url.StartsWith("nocache-")) { isCaching = false; url = url.Replace("nocache-", ""); } if (url.StartsWith("https://exp-picture")) { isCaching = false; } if (url.StartsWith("http://exp-picture")) { isCaching = false; //don't know. } WriteableBitmap img = null; if (isCaching) { img = await StorageManager.TryReadImageCacheAsync(url); } if (img == null) { img = await ExpManager.SimpleRequestImage(url); if (img == null) { throw new ArgumentNullException("img"); } if (isCaching) { await StorageManager.TryWriteImageCacheAsync(url, img); } } else { Debug.WriteLine("# 来自图片缓存: " + url); } Debug.WriteLine("WriteableBitmap img: W:" + img.PixelWidth + " H:" + img.PixelHeight); string base64 = await Utility.WritableBitmapToPngBase64Async(img); await WrapInvokeScriptAsync( webView, "external_getImageSucceed", new string[] { originalUrl, base64 }); } catch (Exception e) { Debug.WriteLine("## image failed:" + e.Message); try { await WrapInvokeScriptAsync( webView, "external_getImageFailed", new string[] { originalUrl, e.Message }); } catch (Exception e2) { Debug.WriteLine("## image failed callback failed:" + e2.Message); App.currentMainPage.ShowNotify("JS API调用失败", "window.external.getImageFailed", Symbol.Cancel); } } } else { await Utility.ShowMessageDialog("未知的 window.external.notify 调用", args.Value.ToString()); } }; }