c#如何在webbrowser中自动关闭网页弹出的js的alert对话框
c#的Winform窗体,用webbrowser读取一个网页,网页的js脚本会弹出一个alert对话框。
请问如何能够阻止这种js的alert对话框弹出?或者自动关闭掉这个js的alert对话框?
查了一些办法,都不起作用,我是新手,请大家给指点一下吧。谢谢了!
------解决方案--------------------
参考以下代码:
using System.Web;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = "http://www.msn.com";
string htmlDocText = TrimScript(GetHtmlContent(url));
File.WriteAllText("D:\\temp.htm", htmlDocText);
webBrowser1.Url = new Uri("D:\\temp.htm");
}
private string GetHtmlContent(string url)
{
string htmlContentText = String.Empty;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
StreamReader streamReader = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
httpWebRequest.Timeout = 5000;
streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.Default);
htmlContentText = streamReader.ReadToEnd();
streamReader.Close();
httpWebResponse.Close();
}
catch { }
finally
{
httpWebResponse.Close();
streamReader.Close();
}
return htmlContentText;
}
private string TrimScript(string htmlDocText)
{
string bodyText = "";
string trimJavascript = "<script type=\"text/javascript\">(.*?)</script>";
Regex regexTrimJs = new Regex(trimJavascript);
bodyText = regexTrimJs.Replace(htmlDocText, "");
return bodyText;
}
}