我有一个Winforms表单,上面有WebBrowser control。
我已经找到了如何通过将C#类的实例附加到ObjectForScripting属性来将C#代码连接到Web浏览器控件中的Javascript,如下所示:
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
}
}
...然后从Javascript中调用它:
<button onclick=window.external.DoSomething('with this')/>
我还没想到的是如何从WebBrowser控件中的表单捕获POST操作的结果,并在我的C#代码中使用它。
答案 0 :(得分:2)
您可以使用jQuery post
代替表单帖子。
假设您的表单的ID为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);
});
});