Check if browser closed manually - c#

In visual studio 2010, working with c#;
I open a browser with:
private IE browser;
private void Set_Browser()
{
string splashUrl = "google.com";
browser= new IE(splashUrl);
}
If a user(person) closes the browser by accident, then my application will not be able to work anymore.
QUESTIONS:
So how do I check if a user closed the browser manually?
Can I unable a user from closing the browser by adding the browser to my
application GUI as a control? [using Windows Forms]
-> How do I do that?
Last question related to this post How to use watin with WebBrowser control? (2 years old, but no decent answer too)
EDIT: The solution in give URL seems to work. Problem is that if I try to send the WebBrowser.ActivateX.. as an object to other class. Then my browser = new IE(..) returns null. It does work when I instantiate it in the form class though. Any solutions?

You can search for the process of internet explorer every x seconds and see if the browser is already running using this code:
bool isRunning = false;
foreach (Process clsProcess in Process.GetProcesses()) {
if (clsProcess.ProcessName.Contains("iexplore"))
{
isRunning = true;
break;
}
}
You can use this article
Or you can add a browser control to your application using this article

One thing you can do is hide the browser to avoid users closing it .. See this SO question.
Hiding Internet Explorer when WatiN is run

Related

Having some trouble when opening chrome browser with Selenium ChromeDriver

I use Selenium ChromeDriver to open chrome browser and load a site into it programmatically.
I install selenium & ChromeDrive from this NuGet
Install-Package Selenium.WebDriver -Version 3.141.0 Install-Package
Selenium.WebDriver.ChromeDriver -Version 77.0.3865.4000
I have some questions:
if target pc has no chrome browser installed then how can i capture it by ChromeDriver ? is it possible?
when i am opening chrome browser by ChromeDriver instance then browser is opening chrome browser with a site but another CUI window is getting opened which i do not want to visible or i want to hide this CUI window. if it is not possible then how could i open this CUI window in minimize state?
a sample CUI window screen shot attached below when i work with FirefoxDriver. the same occur when i work with ChromeDriver instance.
when i executing this code chromeDriver.Close(); then opened chrome browser is getting closed but CUI window is still open. so if i click 5 times on open button then 5 CUI window is getting open along with 5 chrome browser instance which i had to close manually ....which i do not want to manually close it rather i want to close it when browser will be closed....how to achieve it ?
how to capture from code that opened chrome browser is close by this code chromeDriver.Close(); or if user click on cross button of chrome browser to close it?
how to open a new tab in already opened chrome browser instead of opening new chrome browser instance. if no chrome browser is open at all then new chrome browser will be open...how to achieve it by code. this below code opening new chrome browser always....what to change there for my point 5
chromeDriver = new FirefoxDriver(options);
chromeDriver.Navigate().GoToUrl("https://www.google.com");
another issue occur when i work with chrome driver that. it open chrome browser but a notification appear on browser like Chrome is being controlled by automated test software
I search google to hide it and found people said to use this option
options.setExperimentalOption("excludeSwitches", new String[] { "enable-automation" });
at my end this function does not available setExperimentalOption so what to do?
Please answer point wise with sample code.
For question 2,3 you can use below code
(use DriverService.Dispose(); to manually dispose driver service) :
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace MyProject
{
public class Browser : IDisposable
{
bool disposed = false;
IWebDriver Driver;
public Browser()
{
//Chrome Driver copied on startup path
ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(Application.StartupPath, "chromedriver.exe");
//hide driver service command prompt window
driverService.HideCommandPromptWindow = true;
ChromeOptions options = new ChromeOptions();
//hide browser if you need
//options.AddArgument("headless");
//or this to hiding browser
//options.AddArgument("--window-position=-32000,-32000");
//On offer Dona bhatt for disable automated test notification
options.AddExcludedArgument("enable-automation");
//options.AddArgument("disable-infobars");
Driver = new ChromeDriver(driverService, options);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Driver.Close();
Driver.Quit();
Driver.Dispose();
DriverService.Dispose();
}
disposed = true;
}
//this method for navigation
public string Navigate(string url)
{
string page = string.Empty;
try
{
Driver.Navigate().GoToUrl(url);
page =Driver.PageSource;
}
catch
{
}
return page;
}
//this method for wait to an element be visible by element ID
private void WaitUntilLoad(string id, int timeOut)
{
WebDriverWait waitForElement = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut));
try
{
waitForElement.Until(ExpectedConditions.ElementIsVisible(By.Id(id)));
}
catch (WebDriverTimeoutException e)
{
}
}
}
}
Use this class:
using(Browser brw=new Browser())
{
string pageSource=brw.Navigate("My URL");
}
I couldn't post this as a comment because it's too long. I think this question is off topic but I just noted my comments on your items...
This seems to be much to broad. Are you having a problem with any specific issue? All of these seems like things you can research and find out.
1) The chrome driver has to be downloaded and shipped with your app.
2) It might be possible to hide that window but not sure why that would be a hard requirement. I'm going to just say that you can't by default prevent the window from showing.
3) You're going to have to close the chrome windows through your .net code. Selenium isn't going to be graceful enough to terminate all the chrome windows.
4) I'm not sure what you're asking for. What's the problem?
5) I think tabs might be done very differently between browsers, it might not be something natively supported in selenium. There might be some chrome driver commands that can facilitate but I have no idea what they are.
6) Again, this is typically not the preferred experience, I'm guessing one of your packages has a different featureset than whatever you're reading was using.

how to get already opened IE browser handle in selenium?

I have one already opened IE browser , with some url.
After this, I Run below code which will open another IE browser. however it gives me only one window handle in below code.
Is it possible to get previously opened IE browser handle ?
IWebDriver IEdriver = new InternetExplorerDriver();
IReadOnlyCollection<String> browsers = IEdriver.WindowHandles;
foreach (String item in browsers)
{
IEdriver.SwitchTo().Window(item);
String url = IEdriver.Url;
}
I think this is what you're looking for:
String winHandleBefore = driver.getWindowHandle();
//Do whatever operations you have to do
for(String winHandle : IEdriver.getWindowHandles()){
IEdriver.switchTo().window(winHandle);
}
Be careful as what you are trying to do, is not robust solution to write tests cases. If one test case causes browser to crash you will be getting all the test cases failed.
Also I don't think it should be possible to get handles on previously opened window by default, because when you write code
IWebDriver IEdriver = new InternetExplorerDriver();
It calls for a constructor of InternetExplorerDriver class and opens new instance of Internet Explorer.
You can either go for close all browsers before starting your test case execution by killing the ie process from task manager.
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
process.Kill();
}

Webbrowser control not working with attachEvent() [duplicate]

This question already has answers here:
How can I get the WebBrowser control to show modern contents?
(4 answers)
Closed 6 years ago.
My webbrowser control displays an intranet site. It was working fine, until the admin changed a setting in iis that forces ie11 to render in Edge mode. Now my webbrowser control comes up with the script error "object doesn't support property or method attachEvent."
Yes, I know attachEvent is deprecated in ie11. No, I do not have control over the webpage code. No, I can't force the admin to change the setting back again.
I tried using registry settings for my application under browser emulation, using all the codes starting with ie9 up through ie10. None of them had any effect.
Can anyone tell me how to force my webbrowser control to render in such a way as to avoid that script error and continue logging in? The call to attachEvent must be called upon successful login, because when I used bad credentials on the login page the error doesn't come up. When my application was working, the page defaulted to ie 9 compatibility. But it seems the admin's IIS setting has nullified that.
Since you cannot alter the code, I recommend implementing a attachEvent/detachEvent polyfill, like this
HTMLElement.prototype.attachEvent = function(event, cb) {
var onEventName = "on" + event,
obj = this;
if (obj.addEventListener) {
obj.addEventListener(event, cb, false);
} else if (obj.attachEvent) {
obj.attachEvent(onEventName, cb);
} else {
var currentEventHandler = obj[onEventName];
obj[onEventName] = function() {
if (typeof currentEventHandler === 'function') {
currentEventHandler.apply(obj, arguments);
}
cb.apply(obj, arguments);
};
}
};
HTMLElement.prototype.detachEvent = function(event, cb) {
var onEventName = "on" + event,
obj = this;
if (obj.removeEventListener) {
obj.removeEventListener(event, cb, false);
} else if (obj.detachEvent) {
obj.detachEvent(onEventName, cb);
} else {
delete obj[onEventName];
}
};
Here's a working plnkr demonstration (apologies for not using a snippet). I based this code using this old git.
Do note the code is incomplete and not for production, e.g. it is not checking whether HTMLElement, attachEvent, detachEvent exist.

Re-using a specific iexpore window by updating its URL

I have an application that monitors a file, and based on its contents launches a browser using this code:
Process.Start("iexplore", "-nomerge " + fullUrl);
Now as with many small projects, the requirements have changed. The change is that only one browser can be launched from my program at a time.
Also, another program is capable of launching a browser with another url, and I cannot shut it down, eliminating the option of just closing down all instances of iexplore and then launching mine. ( which is what I did originally )
Is there a way to launch a browser and continue to keep control of it so you can update the URL of that specific instance of iexplore using c#?
This code is close to what is in the answer on the duplicate post, but is slightly different, so I am sharing it here.
foreach (SHDocVw.InternetExplorer ie in new SHDocVw.ShellWindowsClass())
{
if (ie.FullName.ToLower().Contains("iexplore") &
ie.LocationURL.ToLower().Contains("&qtype=mine"))
{
ie.Visible = true;
ie.Navigate(fullUrl);
openNewBrowserWindowWindow = false;
}
}
if (openNewBrowserWindowWindow) {
SHDocVw.InternetExplorerClass IE = new SHDocVw.InternetExplorerClass();
IE.Visible = true;
IE.Navigate(fullUrl);
}

Silverlight 2 - Download file - IE Blocks file download

I'm having a problem with IE only in my Silverlight application. Since Silverlight 2 doesn't include a mechanism for file downloads I was left to my own devices to come up with a solution. The way I did it was as follows:
HtmlPage.Window.Navigate(new Uri(sb.ToString(), UriKind.Relative));
My StringBuilder contains the relative url with query string to a *.ashx handler on the server that reads the query string, gets some data from the database, and returns an Excel file.
When I do this I get a blocked file download bar in IE only. I understand that this is a new security "feature" in IE and that it is being blocked because it believes that the download wasn't triggered by the user interaction with the web page. The users can choose to allow the download and that setting seems to be remembered for the rest of the session. However next time they open the page it happens again. Even if the site is in the Trusted zone and even if the popup blocker is configured to allow popups for the site.
Does anyone know how to make IE know that the user did in fact request this file?
I had exactly the same problem. The solution for me was to not use HtmlPage.Window.Navigate, but to instead use a HyperlinkButton and dynamically set the NavigateUri property.
Saving and restoring the app state as suggested above didn't work. Well, it did, but it was impossible to determine when it needed to be done and when it didn't. So, ultimately, it didn't really work.
See this discussion on codeplex....
http://slideshow2.codeplex.com/Thread/View.aspx?ThreadId=60242
Try HtmlPage.PopupWindow instead of HtmlPage.Window.Navigate. This has helped me get around IE's "Automatic prompting for file downloads" setting being disabled by default for Internet zone sites.
This is my code solution to open URL for download and override Automatic prompting for file downloads option issue in IE 8.
It also use HyperlinkButton, but all is called from code:
public class BrowserHelper
{
private sealed class HyperlinkButtonCaller : HyperlinkButton
{
public static void OpenUrl(Uri url)
{
var button = new HyperlinkButtonCaller()
{
NavigateUri = url
};
button.OnClick();
}
}
public static void OpenUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
HyperlinkButtonCaller.OpenUrl(url);
}
}
BrowserHelper.OpenUrl(new Uri(ClientGlobalInfo.Current.ApplicationUrl, "myhandler.ashx"));
In my case only happended the first time (using IE 7), maybe that happens on your local dev instance?
I think there's not much you can do, even MSDN pages tells you that "a message will appear on top of...", things that could mitigate this:
Warn the user that the message will be shown, then once he clicks the app is reset (Store the current app state in the isolated storage, when you receive the reset reload the app with the settings).
Open a popup, and in the popup include and standard HTML button to download.
HTH
Braulio

Categories

Resources