C#开发移动应用系列之使用WebView搭建WebApp应用

返回C#与Java社区
0回复贴,共1页,点击数:1609

参考资料:https://www.cnblogs.com/GuZhenYin/p/7016798.html


namespace ZLFont
{
    /*
     * 
     * 
     */ 

    //JS的方法首字母需要小写,Lower Case Function Calls in JavaScript Land
    public partial class MainWindow : WindowBase
    {
        string basePath = AppDomain.CurrentDomain.BaseDirectory;
        CefSharp.Wpf.ChromiumWebBrowser webView = null;
        public MainWindow()
        {
            //try
            //{
                InitializeComponent();
                this.Loaded += (sender, e) =>
                {
                    //this.YesButton.Content = "确 定";
                    //this.YesButton.Width = 60;
                    //this.NoButton.Content = "取 消";
                    //this.NoButton.Width = 60;
                    //this.YesButton.Click += (ss, ee) =>{MessageBox.Show("确定");};
                    //this.NoButton.Click += (ss, ee) =>{MessageBox.Show("取消");};
                    this.YesButton.Visibility = Visibility.Hidden;
                    this.NoButton.Visibility = Visibility.Hidden;
                };
                //-------------------------------------------初始化
                string startUrl = "wait.html?url=app.html#/welcome";
            //startUrl = "app.html#/welcome";

            ConfigHelper.LoadXML();
            DBCenter.DB = ZoomLa.SQLDAL.SQL.SqlBase.CreateHelper("mssql");
            if (!string.IsNullOrEmpty(ConfigHelper.APPInfo.connstr))
            {
                ZoomLa.SQLDAL.DBCenter.DB.ConnectionString = ConfigHelper.APPInfo.connstr;
                ZLCommon.DB.SqlHelper.ConnectionString = ConfigHelper.APPInfo.connstr;
            }
            try
            {

            }
            catch (Exception ex)
                {
                    MessageBox.Show("检测到配置错误,请先完成配置,原因:" + ex.Message);
                    //startUrl = "wait.html?url=app.html#/config";
                }
                try { FZHelper.LoadXml(); } catch { }
                //-------------------------------------------配置Chrome
                var setting = new CefSharp.CefSettings() { LogSeverity = LogSeverity.Disable, IgnoreCertificateErrors = true };
                CefSharp.Cef.Initialize(setting, true, false);
                webView = new CefSharp.Wpf.ChromiumWebBrowser();
                webView.BrowserSettings.WebSecurityDisabled = true;//允许跨域,否则无法加载file:\\\
                //this.browserContainer.Content = webView;
                //this.Content = webView;
                this.Content = webView;
                webView.RegisterJsObject("wpf", new JavaScriptInteractionObj(webView));
                //webView.Address = "http://www.z01.com";//几种加载方式
                webView.Address = @"file:///" + basePath + "/assest/html/" + startUrl;
                webView.Loaded += WebView_Loaded;
                //webView.LoadingStateChanged += wb_OnLoadingStateChange;
                //-----当加载链接错误时调用
                webView.LoadError += (sender, args) =>
                {
                    // Don't display an error for downloaded files.
                    if (args.ErrorCode == CefErrorCode.Aborted) { return; }
                    var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
                                                  args.FailedUrl, args.ErrorText, args.ErrorCode);
                    //args.Frame.LoadStringForUrl(errorBody, args.FailedUrl);
                };
            //}
            //catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        //-----------------------------------
        //该事件早于Jquery等加载,所以不可在其中写JQuery事件,或需要延时执行
        private void WebView_Loaded(object sender, RoutedEventArgs e)
        {
            //var script = "alert('sadfasdf');";//$('body').css('background-color','red');
            //webView.ExecuteScriptAsync(script);
            //ExecuteJSAndReturnData_Btn_Click(null, null);
            //webView.ShowDevTools();//[debug]
        }
        //void wb_OnLoadingStateChange(object sender, LoadingStateChangedEventArgs e)
        //{
        //    if (e.IsLoading == false)//加载完成时为false,可能会执行多次
        //    {

        //    }
        //}
        //-----------------------------------
        private void CloseCef_Btn_Click(object sender, RoutedEventArgs e)
        {
            Cef.Shutdown();
        }
        private void DevTool_Btn_Click(object sender, RoutedEventArgs e)
        {
            webView.ShowDevTools();
        }
        private void ExecuteJS_Btn_Click(object sender, RoutedEventArgs e)
        {
            var script = "document.body.style.backgroundColor='red';";
            webView.ExecuteScriptAsync(script);
        }
        private void ExecuteJSAndReturnData_Btn_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("function tempFunction() {");
            sb.AppendLine("     var w = window.innerWidth;");
            sb.AppendLine("     var h = window.innerHeight;");
            sb.AppendLine("");
            sb.AppendLine("     return w*h;");
            sb.AppendLine("}");
            sb.AppendLine("tempFunction();");
            // function EvaluateScriptAsync() only returns simple data types (ints, bools, string). 
            //if you need to return a complex object, you need to convert it to JSON first and send the object back as a string.
            var task = webView.EvaluateScriptAsync(sb.ToString());
            task.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    var response = t.Result;
                    if (response.Success == true)
                    {
                        MessageBox.Show(response.Result.ToString());
                    }
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
    public class JavaScriptInteractionObj
    {
        B_FZ_Server serverBll = new B_FZ_Server();
        CefSharp.Wpf.ChromiumWebBrowser webView = null;
        public JavaScriptInteractionObj(ChromiumWebBrowser view)
        {
          
            webView = view;
        }
        public string ErrorFunction()




更多参考:




1楼 2020/04/23 22:57
您未登录,没有发贴权限[点此登录]