Reputation: 61
I have a web browser automation project written in WinForms C#. During the navigation there is a point where the browser does the "are you sure you want to leave this page?" popup. We need this popup, so I cannot remove it from the website code, which means I have to override it in my automation app.
Does anyone have an idea how to do this?
Upvotes: 0
Views: 3398
Reputation: 1
Don't need add anymore. Try it. Work like a charm. ^_^
private void webNavigated(object sender, WebBrowserNavigatedEventArgs e)
{
HtmlDocument doc = webBrowser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text", "function cancelOut() { window.onbeforeunload = null; window.alert = function () { }; window.confirm=function () { }}");
head.AppendChild(s);
webBrowser.Document.InvokeScript("cancelOut");
}
Upvotes: 0
Reputation: 61
and here was the smooth solution..
add a reference to mshtml and add using mshtml;
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) { };
}
);
Upvotes: 2
Reputation: 239704
Are you able to make any changes to the website code?
If so, you might look at exposing an object through ObjectForScripting
, then having the website code check window.external
(and possibly interrogating your object) before it decides to display the popup - so if it can't find your object, it assumes it's being used normally and shows it.
Upvotes: 0