I'm currently trying to change the url of a webBrowser inside a C# winforms application for each user inside a list.
But once I've changed the url I want the browser go get the HTML content of a specified HTML class. So I've started to use the webBrowser1_DocumentCompleted_1 event to grab this content once the browser finished loading the content of the profile.
But my getUserContent function is changing the url way to fast to let the webBrowser1_DocumentCompleted_1 get the content. So it seems like the event is only triggered for the last user inside the list because its redirecting the urls to fast.
Question: Is there a way to stop my function getUserContent to redirect to the next url before the webBrowser1_DocumentCompleted_1 event was triggered and run?
Function to set the webBrowser to a new url:
public void getUserContent()
{
foreach (string username in usernames)
{
currentUser = username;
webBrowser1.Url = new System.Uri("https://www.twitter.com/" + username, System.UriKind.Absolute);
}
}
webBrowser Document loaded event:
private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
HtmlDocument doc = webBrowser1.Document;
HtmlElementCollection divs = doc.GetElementsByTagName("div");
string result = "";
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
{
if (el.GetAttribute("className") == "ProfileHeaderCard")
{
result = el.InnerText;
}
}
MessageBox.Show(result);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I want to get html code from website. In Browser I usually can just click on ‘View Page Source’ in context menu or something similar. But how can I automatized it? I’ve tried it with WebBrowser class but sometimes it doesn’t work. I am not web developer so I don’t really know if my approach at least make sense. I think main problem is that I sometimes get html where not all code was executed. Hence it is uncompleted. I have problem with e.g. this site: http://www.sreality.cz/en/search/for-sale/praha
My code (I’ve tried to make it small but runnable on its own):
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WebBrowserForm
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
for (int i = 0; i < 10; i++)
{
Form1 f = new Form1();
f.ShowDialog();
}
// Now I can check Form1.List and see that some html is final and some is not
}
}
public class Form1 : Form
{
public static List<string> List = new List<string>();
private const string Url = "http://www.sreality.cz/en/search/for-sale/praha";
private System.Windows.Forms.WebBrowser webBrowser1;
public Form1()
{
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.TabIndex = 0;
this.ResumeLayout(false);
Load += new EventHandler(Form1_Load);
this.webBrowser1.ObjectForScripting = new MyScript();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(Url);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
// Final html for 99% of web pages, but unfortunately not for all
string tst = webBrowser1.Document.GetElementsByTagName("HTML")[0].OuterHtml;
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
Application.DoEvents();
webBrowser1.Navigate("javascript: window.external.CallServerSideCode();");
Application.DoEvents();
}
}
[ComVisible(true)]
public class MyScript
{
public void CallServerSideCode()
{
HtmlDocument doc = ((Form1)Application.OpenForms[0]).webBrowser1.Document;
string renderedHtml = doc.GetElementsByTagName("HTML")[0].OuterHtml;
// here I sometimes get full html but sometimes the same as in webBrowser1_DocumentCompleted method
List.Add(renderedHtml);
((Form1)Application.OpenForms[0]).Close();
}
}
}
}
I would expect that in ‘webBrowser1_DocumentCompleted’ method I could get final html. It usually works, but with this site it doesn’t. So I’ve tried get html in my own code which should be executed in web site -> method ‘CallServerSideCode’. What is strange that sometimes I get final html (basically the same as if I do it manually via Browser) but sometimes not. I think the problem is caused because my script start before whole web site is rendered instead after. But I am not really sure since this kind of things are far from my comfort zone and I don’t really understand what I am doing. I’m just trying to apply something what I found on the internet.
So, does anyone knows what is wrong with the code? Or even more importantly how to easily get final html from the site?
Any help appreciated.
You should use WebClient class to download HTML page. No display control necessary.
You want method DownloadString
May be it will be helpful if you add calling of your external function to the end of the body and wrap it by Jquery "ondomready" function. I mean something like this:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
// Final html for 99% of web pages, but unfortunately not for all
string tst = webBrowser1.Document.GetElementsByTagName("HTML")[0].OuterHtml;
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
HtmlElement body = webBrowser1.Document.GetElementsByTagName("body")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "$(function() { window.external.CallServerSideCode(); });";
body.AppendChild(scriptEl);
}
}
[ComVisible(true)]
public class MyScript
{
public void CallServerSideCode()
{
HtmlDocument doc = ((Form1)Application.OpenForms[0]).webBrowser1.Document;
string renderedHtml = doc.GetElementsByTagName("HTML")[0].OuterHtml;
// here I sometimes get full html but sometimes the same as in webBrowser1_DocumentCompleted method
List.Add(renderedHtml);
((Form1)Application.OpenForms[0]).Close();
}
}
Let's say that WPF WebBrowser control shows some navigation errors and the page is not showing.
So there is an exception of WPF WebBrowser control.
I found some similar questions here but it is not what I need.
In fact, I need some method and object that has an exception to get it somehow.
How do we can handle it?
Thank you!
P.S. There is some approach for WinForm WebBrowser Control... Can we do something similar to WPF WebBrowser control?
public Form13()
{
InitializeComponent();
this.webBrowser1.Navigate("http://blablablabla.bla");
SHDocVw.WebBrowser axBrowser = (SHDocVw.WebBrowser)this.webBrowser1.ActiveXInstance;
axBrowser.NavigateError +=
new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(axBrowser_NavigateError);
}
void axBrowser_NavigateError(object pDisp, ref object URL,
ref object Frame, ref object StatusCode, ref bool Cancel)
{
if (StatusCode.ToString() == "404")
{
MessageBox.Show("Page no found");
}
}
P.S. #2 To host WinForm WebBrowser control under WPF App is not an answer I think.
I'm struggling with a similar problem. When the computer loses internet connection we want to handle that in a nice way.
In the lack of a better solution, I hooked up the Navigated event of the WebBrowser and look at the URL for the document. If it is res://ieframe.dll I'm pretty confident that some error has occurred.
Maybe it is possible to look at the document and see if a server returned 404.
private void Navigated(object sender, NavigationEventArgs navigationEventArgs)
{
var browser = sender as WebBrowser;
if(browser != null)
{
var doc = AssociatedObject.Document as HTMLDocument;
if (doc != null)
{
if (doc.url.StartsWith("res://ieframe.dll"))
{
// Do stuff to handle error navigation
}
}
}
}
It's an old question but since I have just suffered through this, I thought I may as well share. First, I implemented Markus' solution but wanted something a bit better as our Firewall remaps 403 message pages.
I found an answer here (amongst other places) that suggests using NavigationService as it has a NavigationFailed event.
In your XAML, add:
<Frame x:Name="frame"/>
In your code-behind's constructor, add:
frame.Navigated += new System.Windows.Navigation.NavigatedEventHandler(frame_Navigated);
frame.NavigationFailed += frame_NavigationFailed;
frame.LoadCompleted += frame_LoadCompleted;
frame.NavigationService.Navigate(new Uri("http://theage.com.au"));
The handlers can now deal with either a failed navigation or a successful one:
void frame_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
e.Handled = true;
// TODO: Goto an error page.
}
private void frame_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
System.Diagnostics.Trace.WriteLine(e.WebResponse.Headers);
}
BTW: This is on the .Net 4.5 framework
It is also possible to use dynamic approach here.
wb.Navigated += delegate(object sender, NavigationEventArgs args)
{
dynamic doc = ((WebBrowser)sender).Document;
var url = doc.url as string;
if (url != null && url.StartsWith("res://ieframe.dll"))
{
// Do stuff to handle error navigation
}
};
I'd been struggling with this issue for some time. I discovered a cleaner way to handle this than the accepted answer. Checking for res://ieframe.dll didn't always work for me. Sometimes the document url is null when a navigation error happened.
Add the following References to you project:
Microsoft.mshtml
Microsoft.VisualStudio.OLE.Interop
SHDocVw (Under COM it's called "Microsoft Internet Controls")
Create the following helper class:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Windows.Controls;
using System.Windows.Navigation;
/// <summary>
/// Adds event handlers to a webbrowser control
/// </summary>
internal class WebBrowserHelper
{
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "consistent naming")]
private static readonly Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
internal WebBrowserHelper(WebBrowser browser)
{
// Add event handlers
browser.Navigated += this.OnNavigated;
// Navigate to about:blank to setup the browser event handlers in first call to OnNavigated
browser.Source = null;
}
internal delegate void NavigateErrorEvent(string url, int statusCode);
internal event NavigateErrorEvent NavigateError;
private void OnNavigated(object sender, NavigationEventArgs e)
{
// Grab the browser and document instance
var browser = sender as WebBrowser;
var doc = browser?.Document;
// Check if this is a nav to about:blank
var aboutBlank = new Uri("about:blank");
if (aboutBlank.IsBaseOf(e.Uri))
{
Guid serviceGuid = SID_SWebBrowserApp;
Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
IntPtr obj = IntPtr.Zero;
var serviceProvider = doc as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
if (serviceProvider?.QueryService(ref serviceGuid, ref iid, out obj) == 0)
{
// Set up event handlers
var webBrowser2 = Marshal.GetObjectForIUnknown(obj) as SHDocVw.IWebBrowser2;
var webBrowserEvents2 = webBrowser2 as SHDocVw.DWebBrowserEvents2_Event;
if (webBrowserEvents2 != null)
{
// Add event handler for navigation error
webBrowserEvents2.NavigateError -= this.OnNavigateError;
webBrowserEvents2.NavigateError += this.OnNavigateError;
}
}
}
}
/// <summary>
/// Invoked when navigation fails
/// </summary>
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "consistent naming")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "consistent naming")]
private void OnNavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
{
this.NavigateError.Invoke(URL as string, (int)StatusCode);
}
}
Then in your window class:
// Init the UI
this.InitializeComponent();
this.WebBrowserHelper = new WebBrowserHelper(this.MyBrowserPane);
// Handle nav error
this.WebBrowserHelper.NavigateError += this.OnNavigateError;
I am developing a c# winform app which controls a website using web browser. I need to perform many events on click of a single button, but many events do not take place until I use a message box to give some sort of lag between events. Below is the code
private void button5_Click(object sender, EventArgs e)
{
try
{
HtmlDocument webDoc = this.webBrowser1.Document;
HtmlElementCollection aTags = webDoc.GetElementsByTagName("a");
string selectedIssue;
selectedIssue = AcknowledgeList.SelectedItem.ToString();
foreach (HtmlElement aElement in aTags)
{
if (aElement.InnerText.Contains(selectedIssue))
{
aElement.InvokeMember("click");
break;
}
}
MessageBox.Show("Device Acknowledged");
this.finalAcknowledge();
}
catch (NullReferenceException connectionError)
{
MessageBox.Show("Connection Error , try again");
}
}
private void finalAcknowledge()
{
try
{
HtmlDocument webDoc = this.webBrowser1.Document;
HtmlElement changeNote = webDoc.GetElementById("#note");
string comment = textBox1.Text;
changeNote.SetAttribute("value", comment);
HtmlElementCollection selectTags
= webDoc.GetElementsByTagName("select");
foreach (HtmlElement selectElement in selectTags)
{
if (selectElement.GetAttribute("name").Equals("status"))
{
selectElement.SetAttribute("value", "6");
}
}
HtmlElement submitButton = webDoc.GetElementById("submit_button");
submitButton.InvokeMember("click");
this.button3.PerformClick();
string selectedIssue;
selectedIssue = AcknowledgeList.SelectedItem.ToString();
AcknowledgeList.Items.Remove(AcknowledgeList.SelectedItem);
AssignToList.Items.Add(selectedIssue);
MessageBox.Show("Device Acknowledged");
this.callShowAssigned();
}
catch (NullReferenceException connectionError)
{
MessageBox.Show("Connection Error , try again");
}
}
Here I have used two message boxes to give some lag between events. I want to get rid of these message boxes and want some other method which can perfrom all the events and I do not have to interrupt the user with some message box or something that is visible
Lag can be done with:
Thread.Sleep(time_to_sleep);
But in this case better to use event:
http://msdn.microsoft.com/en-us/library/5d67hf8a.aspx
webBrowser1.DocumentCompleted+=OnPageLoaded;
When you aElement.InvokeMember("click"), you tell to webBrowser1 make some action: post/get to some page. So webbrowser begins job: it makes call to remote server, gets page, renders it. This take time, which can be longer or shorter. This call is made asynchronous, which means, that your code runs forward without waiting for webbrowser to finish. So what can you do? You can subscribe to webbrowser object events, which will hit when browser control finish work.
//Somewhere before InvokeMember
webBrowser1.DocumentCompleted+=OnPageLoaded;
private void OnPageLoaded(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
//Make your final acknowledgement
//This method will be executed every time, when your page is loaded
}
I have a .NET 2.0 WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The MSDN article doesn't mention this, however.
I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.
Anyone have any experience using one of these and successfully blocking all dialogs, script errors, etc?
EDIT
This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, AxSHDocVW?
EDIT again
Sorry I forgot to mention this... I'm trying to block a JavaScript alert(), with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?
And for an easy way to inject that magic line of javascript, read how to inject javascript into webbrowser control.
Or just use this complete code:
private void InjectAlertBlocker() {
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
string alertBlocker = "window.alert = function () { }";
scriptEl.SetAttribute("text", alertBlocker);
head.AppendChild(scriptEl);
}
This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff.
This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:
window.alert = function () { }
There are many ways to do this, but it is very possible to do. One possibility is to hook an implementation of the DWebBrowserEvents2 interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method.
Like I said, hacky, but it works :)
I can go into more details if I need to.
Bulletproof alert blocker:
Browser.Navigated +=
new WebBrowserNavigatedEventHandler(
(object sender, WebBrowserNavigatedEventArgs args) => {
Action<HtmlDocument> blockAlerts = (HtmlDocument d) => {
HtmlElement h = d.GetElementsByTagName("head")[0];
HtmlElement s = d.CreateElement("script");
IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;
e.text = "window.alert=function(){};";
h.AppendChild(s);
};
WebBrowser b = sender as WebBrowser;
blockAlerts(b.Document);
for (int i = 0; i < b.Document.Window.Frames.Count; i++)
try { blockAlerts(b.Document.Window.Frames[i].Document); }
catch (Exception) { };
}
);
This sample assumes you have Microsoft.mshtml reference added, "using mshtml;" in your namespaces and Browser is your WebBrowser instance.
Why is it bulletproof? First, it handles scripts inside frames. Then, it doesn't crash when a special "killer frame" exists in document. A "killer frame" is a frame which raises an exception on attempt to use it as HtmlWindow object. Any "foreach" used on Document.Window.Frames would cause an exception, so safer "for" loop must be used with try / catch block.
Maybe it's not the most readable piece of code, but it works with real life, ill-formed pages.
You may have to customize some things, take a look at IDocHostUIHandler, and then check out some of the other related interfaces. You can have a fair amount of control, even to the point of customizing dialog display/ui (I can't recall which interface does this). I'm pretty sure you can do what you want, but it does require mucking around in the internals of MSHTML and being able to implement the various COM interfaces.
Some other ideas:
http://msdn.microsoft.com/en-us/library/aa770041.aspx
IHostDialogHelper
IDocHostShowUI
These may be the things you're looking at implementing.
webBrowser1.ScriptErrorsSuppressed = true;
Just add that to your entry level function. After alot of research is when I came across this method, and touch wood till now its worked. Cheers!!
window.showModelessDialog and window.showModalDialog can be blocked by implementing INewWindowManager interface, additionally code below show how to block alert dialogs by implementing IDocHostShowUI
public class MyBrowser : WebBrowser
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
public MyBrowser()
{
}
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
var manager = new NewWindowManagerWebBrowserSite(this);
return manager;
}
protected class NewWindowManagerWebBrowserSite : WebBrowserSite, IServiceProvider, IDocHostShowUI
{
private readonly NewWindowManager _manager;
public NewWindowManagerWebBrowserSite(WebBrowser host)
: base(host)
{
_manager = new NewWindowManager();
}
public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)
{
lpResult = 0;
return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.
}
// Only files of types .chm and .htm are supported as help files.
public int ShowHelp(IntPtr hwnd, string pszHelpFile, uint uCommand, uint dwData, POINT ptMouse, object pDispatchObjectHit)
{
return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.
}
#region Implementation of IServiceProvider
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
{
if ((guidService == Constants.IID_INewWindowManager && riid == Constants.IID_INewWindowManager))
{
ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(INewWindowManager));
if (ppvObject != IntPtr.Zero)
{
return Constants.S_OK;
}
}
ppvObject = IntPtr.Zero;
return Constants.E_NOINTERFACE;
}
#endregion
}
}
[ComVisible(true)]
[Guid("01AFBFE2-CA97-4F72-A0BF-E157038E4118")]
public class NewWindowManager : INewWindowManager
{
public int EvaluateNewWindow(string pszUrl, string pszName,
string pszUrlContext, string pszFeatures, bool fReplace, uint dwFlags, uint dwUserActionTime)
{
// use E_FAIL to be the same as CoInternetSetFeatureEnabled with FEATURE_WEBOC_POPUPMANAGEMENT
//int hr = MyBrowser.Constants.E_FAIL;
int hr = MyBrowser.Constants.S_FALSE; //Block
//int hr = MyBrowser.Constants.S_OK; //Allow all
return hr;
}
}
The InjectAlertBlocker is absolutely correct
code is
private void InjectAlertBlocker() {
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string alertBlocker = "window.alert = function () { }";
element.text = alertBlocker;
head.AppendChild(scriptEl);
}
References needed to be added is
Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references.
Add using mshtml; to your namespaces.
Get a reference to your script element's IHTMLElement:
Then you can use the Navigated event of webbrowser as:
private void InjectAlertBlocker()
{
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string alertBlocker = "window.alert = function () { }";
element.text = alertBlocker;
head.AppendChild(scriptEl);
}
private void webDest_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
InjectAlertBlocker();
}
Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a few Win32 projects tried to use the IE control. Disabling the popups should be done via the event handlers of the control as you already did, but I found that you also need to change the 'Disable script debugging xxxx' in the IE options (or you could modify the registry in your codes) as cjheath already pointed out. However I also found that extra steps needed to be done on checking the navigating url for any downloadable contents to prevent those open/save dialogs. But I do not know how to deal with streaming files since I cannot skip them by looking at the urls alone and in the end I turned to the Indy library saving me all the troubles in dealing with IE. Finally, I remember Microsoft did mention something online that IE is not designed to be used as an OLE control. According to my own experience, every time the control navigates to a new page did introduce memory leaks for the programs!
I had bigger problems with this: loading a webpage that is meant for printing and it displays annoying Print dialog. The InjectBlocker was the only way that worked, but fairly unreliable. Under certain conditions (I am considering it's due that WebBrowser control uses IE engine and this depends on installed IE version) the print dialog still appears. This is a major problem, the solution works on Win7 with IE9 installed, but WinXP with IE8 displays the dialog, no matter what.
I believe the solution is in modifying source code and removing the print javascript, before control renders the page. However I tried that with: DocumentText property of the webbrowser control and it is not working. The property is not read only, but it has no effect, when I modify the source.
The solution I found for my problem is the Exec script:
string alertBlocker = "window.print = function emptyMethod() { }; window.alert = function emptyMethod() { }; window.open = function emptyMethod() { };";
this.Document.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
I managed to inject the code above by creating an extended WebBroswer class and overriding the OnNavigated method.
This seemed to work quite well:
class WebBrowserEx : WebBrowser
{
public WebBrowserEx ()
{
}
protected override void OnNavigated( WebBrowserNavigatedEventArgs e )
{
HtmlElement he = this.Document.GetElementsByTagName( "head" )[0];
HtmlElement se = this.Document.CreateElement( "script" );
mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;
string alertBlocker = "window.alert = function () { }";
element.text = alertBlocker;
he.AppendChild( se );
base.OnNavigated( e );
}
}
Simply from the browser control properties: scriptErrorSupressed=true
The easiest way to do this is :
In the : Webbrowser Control you have the procedure ( standard ) BeforeScriptExecute
( The parameter for BeforeScriptExecute is pdispwindow )
Add this :
pdispwindow.execscript("window.alert = function () { }")
In this way before any script execution on the page window alert will be suppressed by injected code.