Call .Net from javascript in CefSharp 1 - wpf

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

+7
javascript c # cefsharp
source share
3 answers
  • Build WebView via WebView webView = new WebView (url)
  • Then you can call the RegisterJsObject method to register the js object.
  • Use javascript to call this js object.

An example below:

public class CallbackObjectForJs{ public void showMessage(string msg){//Read Note MessageBox.Show(msg); } } WebView webView = new WebView("http://localhost:8080"); webView.RegisterJsObject("callbackObj", new CallbackObjectForJs()); 

JavaScript code in the interface:

 <script type="text/javascript"> callbackObj.showMessage('message from js'); </script > 

Note. The first character cannot be higher than the showMessage method in CallbackObjectForJs

+14
source share

Due to Chromium changes starting with 63.0.0 , significant changes to Javascript Binding occurring. Inherited behavior still works for Single Page Applications and where only one domain is used.

New binding method

The new binding method has many advantages:

  • Snap and untie objects by name
  • Link a subset of objects to various pages (including pop-ups)
  • Delete / untie method
  • Dynamically solves a related object

A 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> 

See Javascript Binding v2 # 2246 and How do you show the .NET class for JavaScript?

Outdated binding

If you perform cross-site navigation, you can no longer use this method to snap objects.

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

A 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> 

See Javascript Binding v2 # 2246 and How do you show the .NET class for JavaScript?

+2
source share

First create an open class in C #, as shown below:

 public class cShaarp_Js { public void calledFromJs(Object object){} } 

And then you have to register this class in your chromeBrowser.

 chromeBrowser = new ChromiumWebBrowser("file:///C:/sample.html"); chromeBrowser.RegisterJsObject("csharp", new cShaarp_Js); 

Now we are done with C #. on the other hand in javascript you can create a callback for this class as shown below:

 function cSharpMetodCall(){csharp.calledFromJs(object);} 
0
source share

All Articles