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 CefAsyncJS
    {
        private string LoginAccount = ConfigurationManager.AppSettings["LoginAccount"];


        public string getLoginAccount()
        {
            return LoginAccount;
        }
        public void setLoginAccount(string data)
        {
            LoginAccount = data ?? "";
        }

}

 

然后注册这个类

//注册C#对象,用来在js里面调用

//注意:RegisterAsyncJsObject的name必须是小写字母开头

//注意:CefAsyncJS类被JS调用的函数也必须是小写字母开头

CefSharpSettings.LegacyJavascriptBindingEnabled = true;
chromeBrowser.RegisterJsObject("cefAsyncJS", new CefAsyncJS(), BindingOptions.DefaultBinder);

 

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

function SetLoginAccount(data) {
    cefAsyncJS.setLoginAccount(data);
}

function GetLoginAccount() {
    return cefAsyncJS.getLoginAccount();
}

原文地址:https://www.cnblogs.com/xbzhu/p/9089852.html