Call C-Sharp from javaScript using CefSharp in WPF app

Datetime:2016-08-23 03:57:47          Topic: JavaScript  WPF           Share

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
        MessageBox.Show(msg);
    }
}

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()
{
    InitializeComponent();
    _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.

<script>
    callbackObj.showMessage("Hello World!");
</script>

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





About List