'Is it possible to send a message from a WPF app that is hosting a CefSharp control, to the web app running in CefSharp like WebView2 can do

With WebVeiw2 you can send a message to a web app running in it using WebView2Ctrl?.CoreWebView2?.PostWebMessageAsJson(message). Is there a way of doing this in CefSharp



Solution 1:[1]

  1. Create a class (I used JavascriptCallbackMessenger) to Set and Run the callbacks.
    public class JavascriptCallbackMessenger
    {
        private IJavascriptCallback _callback;
    
        public void SetCallBack(IJavascriptCallback callback)
        {
            _callback = callback;
        }
    
        public void RunCallback(string message)
        {
            if (_callback != null && _callback.CanExecute)
            {
                _callback.ExecuteAsync(message);
            }
        }
    }
  1. Create an instance of JavascriptCallbackMessenger and register it with the CefSharp control
CefSharpCtrl.JavascriptObjectRepository.Register(JavascriptCallbackMessengerName, _messenger, true, BindingOptions.DefaultBinder);
  1. Set the callback in Javascript as follows (I'm not a JS developer, but this was my solution).
(async function() {
    const cefSharp = (window as any).CefSharp;
    
        await cefSharp.BindObjectAsync(JavascriptCallbackMessengerName);
    
        window.javascriptCallbackMessenger.setCallBack(function(message: string) 
        {
            console.log("messageHandler: " + message);
        })
    })();

I was using typescript, so I had to extend the Window with the newly created variable.

declare global {
  interface Window { javascriptCallbackMessenger: any; }
}

Apologies, but the formatting seems to be a bit "off"!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jklemmack