CefSharp(C#、js交互)

偶尔有个项目调查需要用这个玩意。记录一下

高版本需启用LegacyJavascriptBindingEnabled

CefSharpSettings.LegacyJavascriptBindingEnabled = true;
此为官方demo改造


image.png

js 调用C# 方法

定义处理类

class ScriptCallbackManager
    {
        /// 
        /// 查找电脑信息
        ///  IJavascriptCallback javascriptCallback
        /// 
        public string FindComputerInfo()
        {

            return JsonConvert.SerializeObject(new
            {
                cpu_id = "1",
                disk_id = "2",
                host_name = "联想",
                networkcard = "是的",
                serialNumber = "12233",
                manufacturer = "hello",
                product = "联想",
            });

            //Task.Factory.StartNew(async () =>
            //{

            //    using (javascriptCallback)
            //    {
            //        string response = JsonConvert.SerializeObject(new
            //        {
            //            cpu_id = "1",
            //            disk_id = "2",
            //            host_name = "联想",
            //            networkcard = "是的",
            //            serialNumber = "12233",
            //            manufacturer = "hello",
            //            product = "联想",
            //        });
            //        await javascriptCallback.ExecuteAsync(response);
            //    }
            //});

        }

        public int Div(int dividend, int divisor)
        {
            return dividend / divisor;
        }

    }

C#注册js调用对象

            browser = new ChromiumWebBrowser("F:/winform_tree/js/index.html")
            {
                Dock = DockStyle.Fill,
            };
            browser.RegisterAsyncJsObject("googleBrower", new ScriptCallbackManager(), new CefSharp.BindingOptions { CamelCaseJavascriptNames = false });

            toolStripContainer.ContentPanel.Controls.Add(browser);

js调用处


        
hello

    C#调用js方法

            var findme = function(args){
                alert(args)
                var jsonobj = JSON.parse(args)
                alert(jsonobj.cpu_id)
                
            }
    
            private void GoButtonClick(object sender, EventArgs e)
            {
                //LoadUrl(urlTextBox.Text);
                //后端调用js方法,并传递参数
                string result = JsonConvert.SerializeObject(new
                {
                    cpu_id = "1",
                    disk_id = "2",
                    host_name = "联想",
                    networkcard = "是的",
                    serialNumber = "12233",
                    manufacturer = "hello",
                    product = "联想",
                });
                browser.GetMainFrame().ExecuteJavaScriptAsync(String.Format("findme('{0}')", result));
            }
    

    你可能感兴趣的:(CefSharp(C#、js交互))