///
/// 主要作用是屏蔽IFRAME 类的JS错误
///
public partial class WebbrowserExt : System.Windows.Forms.WebBrowser
{
public string BaseUrl = string.Empty;
public WebbrowserExt()
{
InitializeComponent();
this.AllowWebBrowserDrop = false;
(this.ActiveXInstance as SHDocVw.WebBrowser).NewWindow3 += WebbrowserExt_NewWindow3;
(this.ActiveXInstance as SHDocVw.WebBrowser).FileDownload += WebbrowserExt_FileDownload;
}
public WebbrowserExt(IContainer container)
{
container.Add(this);
InitializeComponent();
this.AllowWebBrowserDrop = false;
var IhtmlDocument3 = (IHTMLDocument3)this.Document.DomDocument;
IhtmlDocument3.enableDownload = false;
(this.ActiveXInstance as SHDocVw.WebBrowser).NewWindow3 += WebbrowserExt_NewWindow3;
(this.ActiveXInstance as SHDocVw.WebBrowser).FileDownload += WebbrowserExt_FileDownload;
}
void WebbrowserExt_FileDownload(bool ActiveDocument, ref bool Cancel)
{
//取消默认的文件下载
if (!ActiveDocument)
Cancel = true;
}
void WebbrowserExt_NewWindow3(ref object ppDisp, ref bool Cancel, uint dwFlags, string bstrUrlContext, string bstrUrl)
{
BaseUrl = bstrUrl;
}
private SHDocVw.IWebBrowser2 Iwb2;
protected override void AttachInterfaces(object nativeActiveXObject)
{
Iwb2 = (SHDocVw.IWebBrowser2)nativeActiveXObject;
Iwb2.Silent = true;
base.AttachInterfaces(nativeActiveXObject);
}
protected override void DetachInterfaces()
{
Iwb2 = null;
base.DetachInterfaces();
}
}
改写的webbrowser如上。
如下是调用。
///
/// 创建新选项卡
///
///
///
private void WebBrowser_NewWindow(object sender, CancelEventArgs e)
{
string strurl;
var wb = new WebbrowserExt();
wb.ScriptErrorsSuppressed = true;
wb.Navigating += new WebBrowserNavigatingEventHandler(WebBrowser_Navigating);
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
wb.NewWindow += new CancelEventHandler(WebBrowser_NewWindow);
wb.ObjectForScripting = this;
try
{
TabPage currentTabPage = tabControls.SelectedTab;
//WebBrowser myWebBrowser = (WebBrowser)currentTabPage.Controls[0];
var myWebBrowser = (WebbrowserExt)sender;
strurl = myWebBrowser.Document.ActiveElement.GetAttribute("href");
if (string.IsNullOrEmpty(strurl))
strurl = myWebBrowser.BaseUrl;
if (string.IsNullOrEmpty(strurl))
strurl = myWebBrowser.StatusText;
if (!strurl.Contains("://"))
strurl = "http://" + strurl;
//刷新页面,不使用缓存设置
if (strurl.Contains("?"))
strurl = strurl + "&t=" + DateTime.Now.Ticks;
else
strurl = strurl + "?t=" + DateTime.Now.Ticks;
if (strurl.Contains(".exe"))
{ }
else
{
wb.Navigate(strurl);
e.Cancel = true;
tabControls.TabPages.Add("新窗口" + SpaceString);
tabControls.TabPages[tabControls.TabPages.Count - 1].Controls.Add(wb);
wb.Dock = DockStyle.Fill;
tabControls.SelectedIndex = tabControls.TabPages.Count - 1;
//清除缓存
CleanTempFiles();
}
}
catch (Exception e2)
{
}
}