CefSharp开发

CefSharp是用chromium内核开发的.net版本浏览器工具。目前只支持X86模式。所以在调试的时候要把平台改为X86

CefSharp开发指引:https://ourcodeworld.com/articles/read/173/how-to-use-cefsharp-chromium-embedded-framework-csharp-in-a-winforms-application

1、C#调用js

 private void btnAlert_Click(object sender, EventArgs e)
        {
            this.browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("alert('这是c#调用的js,给文本框赋值!')");
            //txtAccount
            this.browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('txtAccount').value='在C#里面给页面文本框进行赋值'");
        }

2、js调用C#

首要要创建被调用的C#对象和方法,注意方法名要小写,大写的时候,会调用失败!

public class TestAsyncJS
    {
      
        /// <param name="text"></param>
        public void messageBox(string text)
        {
            MessageBox.Show(text);
        }
    }

然后注册这个类

   //注册C#对象,用来在js里面调用
            this.browser.RegisterAsyncJsObject("CSharpObj", new TestAsyncJS(), BindingOptions.DefaultBinder);

 

这样,就能直接在js页面,调用C#方法

 

<script>  

function ForSharp(){  

           alert("准备调用C#的弹窗提示!");  

//注册的对象名称  

           CSharpObj.messageBox("hello word");  

      }  

  </script>  

猜你喜欢

转载自www.cnblogs.com/xbzhu/p/9089852.html