Search code examples
c#wpfcefsharp

How to using CEFSharp JavascriptObjectRepository in WPF


I want get javascript response,

and follow cef document to do,

this is my step,

first create a html file

...
<button onclick='test()'>click</button>
...
<script>
function test(){ 
  alert('123');
  callbackObj.getMessage('123');
}
</script>

and then I register javascript response method

CefSharpSettings.LegacyJavascriptBindingEnabled = true;
this.MyBrowser.JavascriptObjectRepository.Register("callbackObj", new PagaJavaScriptResponse(), true);

and create class to do PagaJavaScriptResponse

 public class PagaJavaScriptResponse
 {
   public void getMessage(string s)
   {
        ....
   }       
 }

next step to check the register is bound

var isBound = this.MyBrowser.JavascriptObjectRepository.IsBound("callbackObj");

the result is true,

last step to url http://127.0.0.1/index.html

this.MyBrowser.Address = @"http://127.0.0.1:8887/test.html";

here I think when I click button it should be return 123 to my method in C#, but not,

hot it's correct?


Solution

  • I try a solution

    just when page loaded excute this javascript

    this.MyBrowser.WebBrowser.ExecuteScriptAsyncWhenPageLoaded(@"(async function() {await CefSharp.BindObjectAsync('callbackObj', 'bound');})();");
    

    it's will work