Call C-Sharp from javaScript using CefSharp in WPF app

Here’s how you can invoke a C# function from javaScript while using CefSharp in a WPF app.

Step 1: Create a Class with the Method to be Invoked

Create a CallbackObjectForJs class that contains a showMessage function which would be invoked from javascript.

public class CallbackObjectForJs{
    public void showMessage(string msg){//Read Note

Step 2: Register the JS object

The next step is to register the JS object. This can be done by adding the following code in the MainPage.xaml.cs file.

private CallbackObjectForJs _callBackObjectForJs;
public MainWindow()
    _callBackObjectForJs= new CallbackObjectForJs();
    ChromiumWebBrowser.RegisterAsyncJsObject("callbackObj", _callBackObjectForJs);

Step 3: Invoke the C# function from JavaScript

Next, simply invoke the C# function from your javascript code.

    callbackObj.showMessage("Hello World!");

Note: The name of the C# function should start with a small letter.

Vivek Maskara

I am pursuing BTech in Software Engineering from Delhi Technological University. I develop apps, create websites and blog about my app experiences.

Read more:
How to create your first Windows Phone app
How to change the App name and Tile name of your Windows phone app
Data binding in Windows Phone app – One way binding