Reputation: 1115
I have a winform that screen scrapes another application and generates a html file. I'd like to add js to the html file so that when a user clicks a heading, it will send a string and trigger a function within the winform.
I've been researching this for a while now but all of the possible solutions I've seen involve the webbrowser control, which I'm not using and don't intend to use.
Is it possible to call a winform function from an IE page via js?
UPDATE: Now considering a webbrowser control.
Upvotes: 2
Views: 620
Reputation: 2438
If you use WebBrowser
control you can set the object for scripting property to a class with public methods that you want to expose to javascript:
[ComVisibleAttribute(true)] //required
class MyJsInterface
{
public string Test()
{
return "Hello World!";
}
}
browser1.ObjectForScripting = new MyJsInterface(); //for example
Then, you can call the methods in MyJsInterface
from javascript using window.external
object:
//add this script to document.onload or in a script tag at the end of the document
//var headings = document.getElementsByClassName("heading");
//var headings = document.getElementsByTagName("h1");
for (var i = 0; i < headings.length; i++)
{
var element = headings[i];
//element.addEventListener("click", function () {
element.attachEvent("click", function () {
var text = window.external.Test();
alert(text);
}
}
In Internet Explorer versions prior to IE 9, you have to use attachEvent
rather than the standard addEventListener
:
Legacy Internet Explorer and attachEvent
It's also possible to invoke javascript methods from code behind.
Read more here:
Implement Two-Way Communication Between DHTML Code and Client Application Code
Upvotes: 3
Reputation: 14787
Override WndProc
(refer here and here) on your form and listen for WM_LBUTTONDOWN messages. Translate the points based on the location of the Web Browser control. Then use IHtmlDocument (mshtml object library) to access the DOM and find the element at that position (using elementFromPoint).
Upvotes: 1