C#: Calling Javascript values from Web browser control
Many of you will be aware of Webbrowser Control and would have used in different languages like VC, C# or Delphi. By using webbrowser control, you can display your data in any format very easily, since its all about html tags.
Usually it is believed that you can display html only from a file, that you mention in some url (http or file) to display data but in reality you can generate html on runtime without using any HTML file. It is very feasible for situation where user doesn’t have enough rights to create a a file.
OK so just add webbrowser control reference in your project, create an object of IHTMLDocument2 interface and call writeln() method to write html. Interesting part is that it accepts HTML tags as well.
Ok, this problem is solved but there is another issue,that is calling javascript in your C# code. IHTMDocument3 Interface which works with IE5 and above is available as your savior. By using object of type IHTMLDocument3, you can retrieve DIV’s properties by using getElementById() method. So what you can do is that generate the whole html (including javascript) on runtime with a hidden DIV and then fetch value of DIV by calling innerHTML. Code is given below:
object O= null
myurl="about:blank";
this.myBrowser.Navigate(myurl,ref O,ref O,ref O,ref O);
object boxDoc = this.myBrowser.Document;
IHTMLDocument2 doc = (mshtml.IHTMLDocument2)boxDoc;
doc.clear();
doc.writeln("<head><Script language='javascript'>function callme(vals) { document.getElementById(\"test\").innerHTML=vals; }</script></head>");
doc.writeln("<body>Hello <b> World</b>");
doc.writeln("<a href='javascrip t:callme(\"hey\")'>Click here to set innerHTML value of DIV via Javascript</a>");doc.writeln("<div id='test' style='display:none'>foo bar</div></body>");
IHTMLDocument3 doc3=(mshtml.IHTMLDocument3)doc;
myScriptValue=doc3.getElementById("test").innerHTML;
then onClick() event of button, i am displaying value of myScriptValue variable.
Notice the display property of DIV which is set to none, it is working similar to hidden form field and keep in mind,it is not limited with .NET only, you can try it out in VB, Delphi, QT whichever you use for development.
Easy, isn’t it? At least it solved my problem which I was unable to tackle for long time in a pet project.