Robert Harvey
Robert Harvey

Reputation: 180858

How do you capture the result of a POST in the WebBrowser control?

I have a Winforms form with a WebBrowser control on it.

I've already figured out how to connect the C# code to the Javascript in the Web Browser control by attaching an instance of a C# class to the ObjectForScripting property, like this:

public partial class Browser : Form
{
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.ObjectForScripting = new ScriptInterface();
    }
}

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ScriptInterface
{
    public void DoSomething(string data)
    {
        // Do something interesting with data here
    }
}

... and then call it from the Javascript like this:

<button onclick=window.external.DoSomething('with this')/>

What I haven't figured out yet is how to capture the result of a POST operation from a form in the WebBrowser control, and use it in my C# code.

Upvotes: 1

Views: 310

Answers (1)

DavidG
DavidG

Reputation: 119017

You could perhaps use jQuery post instead of a form post.

Assuming your form has an id of myForm:

$( "#myForm" ).submit(function( event ) {     
  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $(this),
  var term = $form.find("input[name='s']").val(),
  var url = $form.attr("action");

  // Send the data using post
  var posting = $.post( url, { s: term } )
      .done(function(data) {
          //Pass the response back to your code
          window.external.DoSomething(data);
      });
});

Upvotes: 2

Related Questions