C#项目中Cef应用之方法互相调用
高版本需启用LegacyJavascriptBindingEnabled
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
定义处理类
class ScriptCallbackManager { /// <summary> /// 查找电脑信息 /// </summary> IJavascriptCallback javascriptCallback /// <param name="javascriptCallback"></param> public string FindComputerInfo() { return JsonConvert.SerializeObject(new { cpu_id = "1", disk_id = "2", host_name = "联想", networkcard = "是的", serialNumber = "12233", manufacturer = "hello", product = "联想", }); } 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调用处
<body> <div>hello</div> <button onclick="findComputerInfo()">获取电脑信息</button> <button onclick="findDiv()">获取电脑信息</button> <ul id="msg"></ul> </body> <script> //设置电脑信息 function callback(data) { data = JSON.parse(data); $("#msg").html(''); $("#msg") .append($("<li>cpu_id:" + data.cpu_id + "</li>")) .append($("<li>disk_id:" + data.disk_id + "</li>")) .append($("<li>host_name:" + data.host_name + "</li>")) .append($("<li>networkcard:" + data.networkcard + "</li>")) .append($("<li>serialNumber:" + data.serialNumber + "</li>")) .append($("<li>manufacturer:" + data.manufacturer + "</li>")) .append($("<li>product:" + data.product + "</li>")); }; function findComputerInfo() { //调用后台C#FindComputerInfo,返回结果回调方法callback googleBrower.FindComputerInfo().then(function(actualResult) { callback(actualResult) }); }; function findDiv() { googleBrower.Div(6, 2).then(function(actualResult) { alert(actualResult) }); } var findme = function(args){ alert(args) var jsonobj = JSON.parse(args) alert(jsonobj.cpu_id) } </script>
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)); }