控制WebBrowser實際上就是控制IE,最簡單的方法就是執行javascript或vbscript,省去了接口的轉換。
如何執行腳本?以前我一直用mshtml中IHTMLWindow2接口的execScript()方法,在Delphi中需要uses MSHTML單元:
- uses MSHTML;
- procedure TForm1.Button1Click(Sender: TObject);
- begin
- (WebBrowser1.Document as IHTMLDocument2).parentWindow.execScript(
- 'alert("hello");', 'javascript')
- end;
在CSharp中則需要在工程添加Micrsoft.mshtml,后來得到在地址欄執行腳本的啟發。用WebBrowser的Navigate()方法更簡單:
- procedure TForm1.Button1Click(Sender: TObject);
- begin
- WebBrowser1.Navigate('javascript:alert("hello");')
- end;
省去了添加引用的麻煩。
如何調用外部的方法?先看一段在IE中添加收藏夾的代碼:
- window.external.AddFavorite(url, title);
腳本中window.external對象就是一個外部對象,AddFavorite()則是這個外部對象的方法!
查了一下資料,原來可以通過IDocHostUIHandler接口的GetExternal()方法,指定腳本的外部對象。
在CSharp中更簡單,有WebBrowser.ObjectForScripting屬性直接對應window.external,參考如下代碼:
- [ComVisible(true)]
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- webBrowser1.DocumentText = @"
- <html>
- <input type=""button"" value=""測試"" onclick=""alert('Zswang 路過');"">
- </html>
- ";
- }
- public void alertMessage(string s)
- {
- MessageBox.Show(s, "囧");
- }
- private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
- {
- webBrowser1.Navigate(@"javascript:
- function alert(str)
- {
- window.external.alertMessage(str);
- }");
- webBrowser1.ObjectForScripting = this;
- }
- }
http://blog.csdn.net/zswang/article/details/3020109