Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
867 views
Welcome To Ask or Share your Answers For Others

1 Answer

Due to Chromium changes starting with 63.0.0 there are major changes Javascript Binding. The legacy behavior still works for Single Page Applications and where only a single domain is used.

New Binding Method

The new binding method has many advantages:

  • Bind and unbind objects by name
  • Bind a subset of objects to different pages (including popups)
  • Delete/unbind a method
  • Resolve a bound object dynamically

Simple example:

public class BoundObject {
    public void showMessage(string msg) {
        MessageBox.Show(msg);
    }
}

browser.JavascriptObjectRepository.Register("boundAsync", new BoundObject(), true);

<script type="text/javascript">
    (async function() {
        await CefSharp.BindObjectAsync("boundAsync", "bound");

        boundAsync.showMessage('Message from JS');
    })();
</script>

For more details visit Javascript Binding v2 #2246 and How do you expose a .NET class to JavaScript?

Legacy Binding

If you perform cross-site navigation's you will no longer be able to use this method to bind objects.

You need to set CefSharpSettings.LegacyJavascriptBindingEnabled = true before you register your first object (RegisterAsyncJsObject).

Simple example:

public class BoundObject {
    public void showMessage(string msg) {
        MessageBox.Show(msg);
    }
}

CefSharpSettings.LegacyJavascriptBindingEnabled = true;
browser.RegisterAsyncJsObject("boundAsync", new BoundAsyncObject());

<script type="text/javascript">
    boundAsync.showMessage('Message from JS');
</script>

For more details visit Javascript Binding v2 #2246 and How do you expose a .NET class to JavaScript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...