Using Angular2 in CefSharp
Asked Answered
L

2

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.
Laniferous answered 11/1, 2018 at 11:21 Comment(0)
H
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();
Housefather answered 11/1, 2018 at 13:33 Comment(3)
If i try to compile it, i get still this Error " Property 'window' does not exist on type 'AppComponent'"Laniferous
Great Thank you its Works!Laniferous
@Laniferous updated my answer according to your second issueHousefather
C
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.

Colton answered 18/3, 2021 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.