calling Javascript from c# using awesomium

2020-02-26 08:25发布

问题:

I'm trying awesomium for create a basic app, I'm testing the js <----> c# communication but this doesn't seem work well...I create a local html and open it..so far so good..but when I try call js nothing happen, no error, no bug, nothing, simply this doesn't call js..

my basic js code is:

 var base = {

    newItem : function(item){
    $("#botones").append('<div class="botonMenu">' + item + '</div>');
  },

  other : function(){
      alert("hi!!");
  }

  }

if I test this inside firebug obviously I can call my functions well and the items are created or the alert box...

now..my c# code is this

//I've wrote this code inside the winForms sample..but change the code for load
//my local file and call js....


WebCore.BaseDirectory = @"C:\Documents and Settings\ME\dummytests\codes\views";
webView.LoadFile("base.html");


JSValue param1 = new JSValue("nameItem");
webView.CallJavascriptFunction("base", "other");
webView.CallJavascriptFunction("base","newItem", param1);
webView.Focus();

the file is load well but the js communication didn't work thanks so much and I hope can help me...this awesomium really look awesome

回答1:

The problem is that you're trying to call the Javascript on the page before it has finished loading. If you wait until after load has completed, you should see it execute correctly.

webView.LoadCompleted += ExecuteJavascript;

WebCore.BaseDirectory = @"C:\Documents and Settings\ME\dummytests\codes\views";
webView.LoadFile("base.html");

...

private void ExecuteJavascript(object sender, EventArgs eventArgs)
{
    JSValue param1 = new JSValue("nameItem");
    webView.CallJavascriptFunction("base", "other");
    webView.CallJavascriptFunction("base", "newItem", param1);
    webView.Focus();
}


回答2:

This is a solution for Awesomium v1.7.0.5. It uses "JSObject" to get the javascript "window" object. From there it calls a javascript function that uses jQuery to dynamically set the text of a "div". This also uses jQuery to call the function when the document is ready.

One can use the JSObject.Bind method to call C# methods from javascript.

Head:

<script type="text/javascript">

    function setDivText(s)
    {
        $("#msgDiv").text(s);
    }

    $(document).ready(function () {

        setDivText("This is the start up text.");

    });
</script>

Body:

<body>
<p>Test...</p>
<p></p>

<div id="msgDiv"></div>

</body>

C#:

This uses WPF WebControl with Name of "webView" inside a Button Click event handler.

  using Awesomium.Core;

  ...

  private void Button1_Click(object sender, RoutedEventArgs e)
  {
     JSObject window = webView.ExecuteJavascriptWithResult("window");

     if (window == null)
        return;

     using (window)
     {
        window.InvokeAsync("setDivText", "You pressed button 1.");            
     }
  }


标签: c# awesomium