CefSharp F12打開DevTools查看console js和c#方法互相調用

原文:CefSharp F12打開DevTools查看console js和c#方法互相調用html

 

winform嵌入chrome瀏覽器,修改項目屬性 生成 平臺爲x86web

1.nuget安裝cefsharp

2.實例化瀏覽器

ChromiumWebBrowser b;chrome

private void Form1_Load(object sender, EventArgs e)
{json

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);c#

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


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

3.響應F12打開控制檯console

 

  public class KeyBoardHander : IKeyboardHandler
    {
        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;
            const int VK_F5 = 0x74;
            if (windowsKeyCode == VK_F5)
            {
                browser.Reload(); //此處能夠添加想要實現的代碼段
            }
            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函數.promise

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

相關文章
相關標籤/搜索