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();
}