1. 程式人生 > 其它 >CefSharp F12開啟DevTools檢視console js和c#方法互相呼叫

CefSharp F12開啟DevTools檢視console js和c#方法互相呼叫

 

winform嵌入chrome瀏覽器,修改專案屬性 生成 平臺為x86

1.nuget安裝cefsharp

2.例項化瀏覽器

ChromiumWebBrowser b;

private void Form1_Load(object sender, EventArgs e)
{

CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("--disable-web-security","1");//關閉同源策略,允許跨域
settings.CefCommandLineArgs.Add("ppapi-flash-version", "18.0.0.209");//PepperFlash\manifest.json中的version
settings.CefCommandLineArgs.Add("ppapi-flash-path", "PepperFlash\\pepflashplayer.dll");
settings.CefCommandLineArgs.Add("--enable-system-flash", "1");//使用系統flash
Cef.Initialize(settings);

/*以上設定未測試是否可行*/


b = new ChromiumWebBrowser("http://localhost:57531/views/Map/scene.html");
this.Controls.Add(b);
b.Dock = DockStyle.Fill;
b.KeyboardHandler = new CEFKeyBoardHander();
}

3.響應F12開啟控制檯console

public class CEFKeyBoardHander : IKeyboardHandler
{//https://bbs.csdn.net/topics/392375553
public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
{
if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode))
{
var key = (Keys)windowsKeyCode;
switch (key)
{
case Keys.F12:
browser.ShowDevTools();
break;

case Keys.F5:

if (modifiers == CefEventFlags.ControlDown)
{
//MessageBox.Show("ctrl+f5");
browser.Reload(true); //強制忽略快取

}
else
{
//MessageBox.Show("f5");
browser.Reload();
}
break;


}
}
return false;
}

public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
{
return false;
}
}

 

3.js呼叫c#方法

public class JsCallMethods
{
public string Test(string msg)
{
return "Return value:" + msg;


/*如果此處要操作winform介面相關的,則需要使用beginInvoke將請求封送至winform主執行緒中,定義一個全域性靜態的主視窗類例項  public static Form1 MainForm;主窗體的load事件中MainForm=this;否則會報錯:System.InvalidOperationException:“執行緒間操作無效: 從不是建立控制元件“Form1”的執行緒訪問它。” 如果要在BeginInvoke之後返回值給前臺請使用Invoke代替beginInvoke或者在返回值之前使用EndInvoke函式.

Form1.MainForm.BeginInvoke(new Action(()=> {
var frm = new XXWindow();
frm.Show();

/*Invoke之後返回值得情況示例*/

var str = "";

//Form1.MainForm.Invoke(...);
var iresult=Form1.MainForm.BeginInvoke(new Action(() =>
{
if (frm != null && !frm.IsDisposed)
{
str=frm.PlayByIndex(index,brand,ip,port,user,pwd,channel,isMainStream);

}
else
{
str= "播放視窗未例項化.";
Thread.Sleep(3000); //阻塞3s,後返回值給前臺
}
}));
////while (!iresult.AsyncWaitHandle.WaitOne(-1, false))
////{
//// Console.Write("*");
////}
var obj=Form1.MainForm.EndInvoke(iresult);
return str;

 

*/


}));


}
}

將以下程式碼載入Cef.Initialize(settings)之後

CefSharpSettings.LegacyJavascriptBindingEnabled = true;//新cefsharp繫結需要優先申明

browser.RegisterAsyncJsObject("MainForm", new JsCallMethods(), new CefSharp.BindingOptions() { CamelCaseJavascriptNames = false });
Cef.AddCrossOriginWhitelistEntry("*", "http", "*", true);

js呼叫並獲取返回值:

var promise = MainForm.Test("123");
promise.then(function (v) {

alert(v);
})

 3.2下載檔案

public void Download(string path)
{
try
{
HttpDownloadFile(path, Application.StartupPath, true, (fileName, contenType, bytes, totalLength, streamLength) =>
{
System.Diagnostics.Process.Start(fileName);
});
}
catch (Exception ex)
{
MessageBox.Show("操作失敗:"+ex.Message);
}
}

/// <summary>
/// 檔案下載
/// </summary>
/// <param name="url">所下載的路徑</param>
/// <param name="path">本地儲存的路徑</param>
/// <param name="overwrite">當本地路徑存在同名檔案時是否覆蓋</param>
/// <param name="callback">實時狀態回掉函式</param>
/// Action<檔名,檔案的二進位制, 檔案大小, 當前已上傳大小>
public static void HttpDownloadFile(string url, string path, bool overwrite, Action<string, string, byte[], long, long> callback = null)
{
// 設定引數
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//傳送請求並獲取相應迴應資料
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//獲取檔名
string fileName = response.Headers["Content-Disposition"];//attachment;filename=FileName.txt
string contentType = response.Headers["Content-Type"];//attachment;

if (string.IsNullOrEmpty(fileName))
fileName = response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1];
else
fileName = fileName.Remove(0, fileName.IndexOf("filename=") + 9);

fileName = HttpUtility.UrlDecode(fileName);
//直到request.GetResponse()程式才開始向目標網頁傳送Post請求
using (Stream responseStream = response.GetResponseStream())
{
long totalLength = response.ContentLength;
///檔案byte形式
byte[] b =new byte[totalLength];
//建立本地檔案寫入流
if (System.IO.File.Exists(Path.Combine(path, fileName)))
{
fileName = DateTime.Now.Ticks + "-"+fileName ;
}
var fullPath = Path.Combine(path + "\\downloads", fileName);
using (Stream stream = new FileStream(fullPath, overwrite ? FileMode.Create : FileMode.CreateNew))
{
byte[] bArr = new byte[1024];
int size;
while ((size = responseStream.Read(bArr, 0, bArr.Length)) > 0)
{
stream.Write(bArr, 0, size);

}
}
callback.Invoke(fullPath, contentType, b, totalLength, 0);
}
}

js呼叫

 MainForm.Download("http://192.168.18.199/test.xls");


4.c#呼叫js方法

function jsMethod(param) {
alert("jsMethod called param is :" + param);
}

 

C#呼叫

b.ExecuteScriptAsync("jsMethod(123)");

 

 

 

From: https://www.cnblogs.com/xuejianxiyang/p/9981398.html