CefSharp is a Chromium browser embedded to an application.

In my case, I’m using WinForms (CefSharp.WinForms v57.0.0).

What I want to achieve here:

When user click on the <a> element, the C# code there need to perform some action.

How it can be done

In C# code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
...
public void InitBrowser()
{
...
browser = new ChromiumWebBrowser("http://yoursite.com");
...
var eventObject = new ScriptedMethodsBoundObject();
eventObject.EventArrived += OnJavascriptEventArrived;
browser.RegisterJsObject("boundEvent", eventObject, options: BindingOptions.DefaultBinder);
}
...
public static void OnJavascriptEventArrived(string eventName, object eventData)
{
var jsonString = eventData.ToString();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var dataDict = serializer.Deserialize<Dictionary<string, object>>(jsonString);
Console.WriteLine("Event arrived: {0}", eventName); // output 'click'
switch (eventName)
{
case "click":
{
// do whatever you want here
Console.WriteLine(dataDict["data1"]); // output 'foo'
Console.WriteLine(dataDict["data2"]); // output 'bar'
break;
}
}
}

In JavaScript code

1
2
3
4
5
6
7
8
9
10
$('a').click(function(e) {
if (!window.boundEvent) {
console.log('window.boundEvent does not exist.');
return;
}
window.boundEvent.raiseEvent('click', JSON.stringify({
data1: 'foo',
data2: 'bar'
}));
});