7

I'm looking for a way to run my Angular2 application in a CefSharp control and establish a communication in both directions. Let me give you two examples:

  1. I have a button in my Angular app and want my CefSharp to output a message box (Only as an example). I know how to get into the javascript code, but I can't compile my AngularApp, if you add a class from the C#, because it doesn't know this.

C# code:

private void RegisterJsObjects()
{           
    _browser.RegisterJsObject("cefTestClass", new TestClass());
}

class TestClass
{
    public void csF(string message) 
    {
        MessageBox.Show(message, "#C", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
    }
}

Angular code:

<button (click) ="cefTestClass.csF('text')"> C# Button </button>

  1. I want to call Angular functions from my CefSharp application, because they get different names after compiling, I can't get access to them.
L. Guthardt
  • 1,990
  • 6
  • 22
  • 44
MartinZyk
  • 192
  • 1
  • 12

2 Answers2

10

The registered object is bound to the window object of javascript. You missed out the word window at the invocation. You have to call it like this:

<button (click) ="appComponentFunction()"> C# Button </button>

and in your AppComponent:

appComponentFunction(){
    window['cefTestClass'].csF('text');
}

It is important that the methods of your registered object begins with a lower case letter, otherwise javascript doesn't execute them.


If you want to call a Angular function from c# you can register a callback in your c#-class like this:

private IJavascriptCallback callback;

public void registerCallback(IJavascriptCallback callback)
{
    this.callback = callback;
}

now you must define your callback in your Angular app (eg. in the NgOnInit in your root-component):

window['cefTestClass'].registerCallback(function() {
  window.alert("Hallo");
});

now you can call the function any time in c#:

callback.ExecuteAsync();
J. Wiesner
  • 101
  • 7
0

As noted here: https://github.com/cefsharp/CefSharp/issues/2990, the "RegisterJsObject" function is obsolete.

Here's the recommended replacement:

//Old method
browser.RegisterJsObject("bound", new BoundObject(), options: BindingOptions.DefaultBinder);

//Replaced with
CefSharpSettings.WcfEnabled = true;
browser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync:false, options: BindingOptions.DefaultBinder);

Async function also replaced in similar fashion.

Prethen
  • 269
  • 1
  • 11