1,首先引入using mshtml;在类名称前添加[ComVisible(true)]
2,在webBrowser1.Navigate("http://xxxxx")时,添加事件 webBrowser1.Navigated+=new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);(webBrowser1为webBrowser控件实例)
3,在webBrowser1_Navigated函数中添加如下内容:
public void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
IHTMLWindow2 win = (IHTMLWindow2)webBrowser1.Document.Window.DomWindow;
string s = @"function confirm() {";
s += @"return true;";
s += @"}";
s += @"function alert(str)";
s += @"{";
s += @"window.external.alertMessage(str);";
s += @"}";
win.execScript(s, "javascript");
webBrowser1.ObjectForScripting = this;
}
alertMessage(str)为自定义函数,形式如下:
public void alertMessage(string s)
{
MessageBox.Show("接收到alert消息:"+s); //换成你自己想要执行的动作
}