How to Close the selenium webdriver if the url is not opening - java

There are many answers(driver.close()) there for this questions but none of them are helped me.
I try to open a website using selenium web driver for every minute.If the website was not opened within a minute code need to close the driver, but it is not closing.Because,the web page title is displaying as connecting.Please help me to work on this.

There is not a direct way to accomplish this unless you kill the browser and quit the driver instance. The easiest way probably is to add some hardcoded delay and killed the session with JavaScript
driver.get("something");
Thread.sleep(1000);
//Alternative to javaScript is to use Actions Class and send ESC key to stop execution
//Actions actions = new Actions(driver);
//actions.sendKeys(Keys.ESCAPE);
((JavascriptExecutor) driver).executeScript("window.stop;");
driver.quit();
Edit
If you want to add another way to bypass the killing of the session if in case the website loads properly try this
driver.get("");
try {
(new WebDriverWait(driver, 1)).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("something we know should exist if page load");
} catch (Exception ex) {
//Alternative to javaScript is to use Actions Class and send ESC key to stop execution
//Actions actions = new Actions(driver);
//actions.sendKeys(Keys.ESCAPE);
((JavascriptExecutor) driver).executeScript("window.stop;");
driver.quit();
}

Related

How to handle iOS App session timeouts using Java and Appium in Mobile Native

I am working on an app, where i get a timeout after certain period of inactivity. I want to capture that and click on 'Continue' when that alert comes up so that the test is not interrupted.
Since this alert is not triggered by any action, it is challenging to predict when this occurs. Any suggestions on how this can be handled?
Performing a check like below after each and every step doesn't look like an ideal solution.
if (alert.exists()){
button.click;
}
You can try smth like this:
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
} catch (Exception e) {
System.out.println(" no alert visible after 30 sec.");
}

Disable popup "Restore Pages? Chrome didn't shut down correctly." in selenium webdriver Java

Though I have seen some related questions, I am putting this question again as I am still facing the issue.
I have a website that asks for login verification code on first time login and then it does not ask in further login instances. If I dont use a custom browser profile, the site asks verification code every time when selenium runs the login. Hence I have used customed browser profile as below (this is not the question)
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
Then, After the test is finished, I quit the browser using
driver.quit();
Problem is, next time I run the test again, the chrome browser opens with the popup "Restore Pages? Chrome didn't shut down correctly." and the site asks for verification code again after login. Entering verification code is not part my script, so the script fails. Then I close the browser manually by clicking on the X on the top corner.
Then I run the test again, chrome browser opens Normally without the popup and the site does not ask for verification code, login is successful. then, script closes browser itself by the driver.quit().
Then I run the test again, chrome browser opens with the popup and test fails again.
This shows that driver.quit() is not closing the browser correctly.
I have tried several settings, but still the popup is coming.
preferences file -> "exit_type":"none" (as well as "normal") and exit cleanly = true
site settings -> pop-ups and redirects -> Blocked (recommended)
I have also tried checking alerts exists or not, but it says "No alert". Script does not detect the popup as alert.
How can I make sure the browser is opened NORMALLY every next time after driver.quit() closes the browser in the previous test run? Please help.
Below is my code: I use chrome extension, so I cannot disable extension also.
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("--disable-notifications");
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");
I dont want to use incognito mode, because I need to retain the cookies and passwords to prevent the login verification code issue mentioned earlier.
I solved this issue setting the exit_type to normal in the preferences after set up the user dir.
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
In your case will be something like this
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");

Avoid the execution stop while browsing in Selenium WebDriver

I need help for this thing that's driving me crazy.
I want to check the browser url in and endless loop, waiting a little (Thread.Sleep) between a loop and another, to not overload the CPU. Then, if the browser url is what I need, I want to add/change/remove an element through Javascript before the page is fully loaded, otherwise the person who uses this could see the change. (I don't need help for the javascript part)
But there's a problem: it seems that in Selenium Webdriver when I navigate to a page (with .get(), .navigate().to() or also directly from the client) the execution is forced to stop until the page is loaded.
I tried to set a "fake" timeout, but (at least in Chrome) when it catches the TimeoutException, the page stops loading. I know that in Firefox there's an option for unstable loading, but I don't want to use it because my program isn't only for Firefox.
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.MILLISECONDS); // Fake timeout
while (true) {
try {
// If the url (driver.getCurrentUrl()) is what I want, then execute javascript without needing that page is fully loaded
// ...
// ...
}
catch (TimeoutException e) {
// It ignores the Exception, but unfortunately the page stops loading.
}
Thread.sleep(500); // Then wait some time to not overload the cpu
}
}
I need to do this in Chrome, and if possible with Firefox and Internet Explorer. I'm programming in Java. Thanks in advance.
Selenium is designed to stop once the webpage is loaded into the browser so that it can proceed with execution.
In your case there are two options:
1) If the browser url will change automatically (ajax) at an arbitrary time, then just keep getting browser url until your condition satisfies.
while(currentURL.equals("Your Condition")){
currentURL = driver.getCurrentUrl();
Thread.sleep(2000);
}
2) If the browser needs to be refreshed use the refresh method in a loop until you get your desired url
while(currentURL.equals("Your Condition")){
driver.navigate().refresh();
currentURL =
Thread.sleep(2000);
}
As know, if user tried with driver.get("url");, selenium waits until page is loaded (may not be very long). so if you want to do some thing on navigate to URL without waiting total load time use below code instead of get or navigate
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("window.open('http://seleniumtrainer.com/components/buttons/','_self');");
After this used
driver.findElement(By.id("button1")).click();
to click on button but i am getting no such element exception, so i am expecting its not waiting for page load. so times page loading very quick and click working fine.
i hope this will help you to figure it out your issue at start up. for loop i hope solution already provided.
Thanks

Selenium catch popup on close browser

I'm trying to test that when I close my window a popup shows with a warning message.
I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show.
I could test it by using the awt Robot and sending alt+f4 but this doesn't seem too reliable.
What would be the proper way to do this?
Instead of using driver.quit() to close the browser, closing it using the Actions object may work for you. This is another way to close the browser using the keyboard shortcuts.
Actions act = new Actions(driver);
act.sendKeys(Keys.chord(Keys.CONTROL+"w")).perform();
Or, if there are multiple tabs opened in driver window:
act.sendKeys(Keys.chord(Keys.CONTROL,Keys.SHIFT+"w")).perform();
You need to switch into the alert if the alert is displayed accept or dismiss it and then call driver.quit();
if(driver.switchTo().alert() != null)//switches only if alert is displayed
{
Alert alert = driver.switchTo().alert();
alert.dismiss(); // alert.accept();
}
driver.quit();
Hope this helps you...kindly get back if it is not working for you

Webdriver - HTTP authentication dialog

I have a very simple selenium-webdriver script. I would like to do HTTP authentication using webdriver.
Script:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.httpwatch.com/httpgallery/authentication/");
driver.findElement(By.id("displayImage")).click();
Thread.sleep(2000);
driver.switchTo().alert().sendKeys("httpwatch");
Issue:
driver.switchTo().alert().sendKeys("httpwatch");
throws
org.openqa.selenium.NoAlertPresentException: No alert is present
Question:
Does Webdriver find only an alert dialog as alert?
What are my options to automate this without using AutoIt OR http:// username:password #somesite
EDIT
Alert has below method and does not seem to have been implemented yet.
driver.switchTo().alert().authenticateUsing(new UsernameAndPassword("username","password"))
The problem is that this is not a javascript popup hence you cannot manipulate it via selenium's alert().
If both AutoIt and submitting credentials in the URL (the easiest option - just open up the url and click "Display Image") are not options for you, another approach could be to use AutoAuth firefox addon to automatically submit the previously saved credentials:
AutoAuth automatically submits HTTP authentication dialogs when you’ve
chosen to have the browser save your login information. (If you’ve
already told the browser what your username and password are, and
you’ve told it to remember that username and password, why not just
have it automatically submit it instead of asking you each time?)
Following the answer suggested in HTTP Basic Auth via URL in Firefox does not work? thread:
Install AutoAuth Firefox plugin;
Visit the site where the authentication is needed. Enter your username and password and make sure to choose to save the credentials;
Save AutoAuth installation file at your hard drive: at the plugin page, right click at “Add to Firefox” and “Save link as”;
Instantiate Firefox webdriver as following:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
File pluginAutoAuth = new File("src/test/resources/autoauth-2.1-fx+fn.xpi");
firefoxProfile.addExtension(pluginAutoAuth);
driver = new FirefoxDriver(firefoxProfile);
Also, in a way similar to AutoIt option - you can use sikuli screen recognition and automation tool to submit the credentials in the popup.
Also see other ideas and options:
Support BASIC and Digest HTTP authentication
Handling browser level authentication using Selenium
The Basic/NTLM authentication pop-up is a browser dialog window. WebDriver (Selenium 2.0) cannot interact with such dialog windows. The reason for this is because WebDriver aims solely at mimicking user interaction with websites, and browser dialog windows are currently not in that scope. JavaScript dialog windows, are part of the website, so WebDriver can handle those. In Selenium 1.0 it is possible to do basic authentication.
So how to solve this issue? 1) Authentication via URL http://username:password#website.com 2) Use a browser plugin that will handle the Basic/NTLM autentication 3) Use a local proxy that will modify the request header and pass along the username/password and 4) Make use of a robot, like AutoIt, or some Java library.
Option 1: is the easiest and has the least impact on the system/test. Option 2: has a high browser impact as your loading plugins. Also every browser uses its own plugin and it's possible that the required plugin for a certain browser is not available. Option 3: Works well with HTTP, but HTTPS requires custom certicates thus not always an option. Not much impact on both system and test. Option 4: Mimics keyboard presses, its a go to solution but prone to errors. Only works when the dialog window has focus and it is possible that this is not always the case.
I faced same issue, and got some concrete solution using robot class. Its workaround or solution, Let see , but it works.
public class DialogWindow implements Runnable {
#Override
public void run() {
try {
entercredentials();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void entercredentials() InterruptedException {
Thread.sleep(5000);
try {
enterText("username");
enterSpecialChar(KeyEvent.VK_TAB);
enterText("password");
enterSpecialChar(KeyEvent.VK_ENTER);
} catch (AWTException e) {
}
}
private void enterText(String text) throws AWTException {
Robot robot = new Robot();
byte[] bytes = text.getBytes();
for (byte b : bytes) {
int bytecode = b;
// keycode only handles [A-Z] (which is ASCII decimal [65-90])
if (bytecode> 96 && bytecode< 123)
bytecode = bytecode - 32;
robot.delay(40);
robot.keyPress(bytecode);
robot.keyRelease(bytecode);
}
}
private void enterSpecialChar(int s) throws AWTException {
Robot robot = new Robot();
robot.delay(40);
robot.keyPress(s);
robot.keyRelease(s);
}
}
How to call it
WebDriver driver= new FirefoxDriver()// or any other driver with capabilities and other required stuff
(new Thread(new DialogWindow())).start();
driver.get(url);

Categories