Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular2 in CefSharp

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.
like image 852
MartinZyk Avatar asked Jan 11 '18 11:01

MartinZyk


1 Answers

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();
like image 86
J. Wiesner Avatar answered Nov 03 '22 02:11

J. Wiesner