Search code examples
javascriptc#cefsharp

Call .Net from javascript in CefSharp 1 - wpf


I'm just learning C# WPF and has been successfully implemented CefSharp, how to call .NET function from javascript, that is loaded in CefSharp?


Solution

    1. Construct WebView via WebView webView = new WebView(url)
    2. Then you can invoke RegisterJsObject method to register a js object.
    3. Use javascript to invoke this js object.

    The example as below:

    public class CallbackObjectForJs{
        public void showMessage(string msg){//Read Note
            MessageBox.Show(msg);
        }
    }
    
    WebView webView = new WebView("http://localhost:8080");
    webView.RegisterJsObject("callbackObj", new CallbackObjectForJs());
    

    javascript code at frontend:

    <script type="text/javascript">
        callbackObj.showMessage('message from js');
    </script >
    

    Note: The first character can't be upper of showMessage method at CallbackObjectForJs