C#:Calling Javascript value from Webbrowser Control
Many of you will be aware of our mighty 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.Normally it is believed that you can display html only from a file,that is you mention some url (http or file) to display data but 2 days back i learnt that 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.Fortunately i found this website which discussed the way to generate HTML on runtime.So just add webbrowser control reference in your project,create an object of IHTMLDocument2 and call writeln() method to write html,intresting part is that it accepts HTML tags as well.
Ok,i solved one hurdle but there was another issue,that is calling javascript in your C# code,I googled alot and found very difficult solutions to tackle this like URL monikering,calling Jscript compiler etc etc.I was looking for some easy solution, IHTMDocument3 which worls with IE5 and above was available to pull me out of hell.By using object of type IHTMLDocument3,you can retrieve DIV`s properties by using getElementById() method.So what i did that i generated 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>HI <b> ADNAN</b>");
doc.writeln("<a href='BLOCKED SCRIPTcallme(\"hey\")'>Click here to set innerHTML value of DIV via Javascript</a>");
doc.writeln("<div id='test' style='display:none'>Adnan Ahmad Siddiqi</div></body>");
IHTMLDocument3 doc3=(mshtml.IHTMLDocument3)doc;
myScriptValue=doc3.getElementById("test").innerHTML;
then onClick() event of button,i am displaying value of myScriptValue variable.Output screenshots are given below:
http://www.geocities.com/kadynan/sh1.jpg
http://www.geocities.com/kadynan/sh2.jpg
Easy,isn't it?Atleast it solved my problem which I was unable to tackle for long time in a personal project(classified :D )
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 in VB,Delphi ,QT whatever you use for development.