Update Jun/11/2015: Please view the correct answer below
You can look at this: Web browser control: How to capture document events?
But that shows the use of a COM add-in. However, as of .net 4.5, this can be done plain-out-of-the-box.
Say this is a small html page:
<html>
<head>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function() {
$('input').click(function(){
alert("hello");
$(document).trigger("foo");
});
});
</script>
</head>
<body>
<input type="button" value="Trigger"/>
</body>
</html>
This page will trigger a custom event on the document. I am hosting this page using a python web server @ localhost:4542. (That is not shown here). You have to wait for the html document to load, and post that, attach the event handler.
using System;
using System.Windows.Forms;
namespace winformWebBrowser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:4542");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.AttachEventHandler("foo", new EventHandler(delegate(object s, EventArgs k)
{
MessageBox.Show("foo");
}));
}
}
}
But what if you want to custom data exposed on the event...? As of now, I don't have an answer for that part...but you can devise many ways to achieve this. Like for e.g., put all necessary data in a hidden field somewhere on the html document...and query that out from c# code
Update Jun/11/2015: I sort of remember that the code worked the first time I tried it. However, on subsequent testing it failed everytime. It seems you can only handle pure DOM events - like click, mouseover, mousemove, etc. Hence your final approach to write code around this limitation.