Selenium 2 WebDriver UnhandledAlertException Java - java

Now before I start getting scolded, I DID read through most of the existing questions about this and applied different solutions (which mostly repeat the same thing), but it still does not work for me.
I have a maven project with all necessary dependencies, and the website in testing is done specifically for IE and requires me to have a specific certificate in order to access it. I have the certificate for it, and when I go onto the website, before it loads the page it asks me to confirm that I have the certificate and I need to confirm on the pop-up window, THEN the login page fully loads.
I have done to typical:
WebDriverWait wait = new WebDriverWait(driver, 3);
try {
// Handle alert box
driver.navigate().to("https://ke.m-pesa.com/ke/");
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
catch(Exception e) {
//whatever
}
Can you tell me where I am going wrong? So far I have used only Selenium RC up till now so this webdriver stuff is still kind of new to me. Please tell me if you need any more info I need to provide.
Why do I still get the UnhandledAlertException?? and why can't I access the login page until I manually press the OK button?

Did you try using Robot? Something like :
Alert alert = driver.switchTo().alert();
Robot a = new Robot();
a.keyPress(KeyEvent.VK_ENTER);
Why robot and not Actions
From this answer :
There is a huge difference in terms of how do these tools work.
Selenium uses the WebDriver API and sends commands to a browser to
perform actions (through the "JSON wire protocol").
Java AWT Robot uses native system events to control the mouse and
keyboard.
If you are doing browser automation, ideally, you don't ever use
things like Robot since usually the functionality provided by selenium
is more than enough. Though, there are cases when there is a browser
or native OS popup opened, for example, to upload/download a file -
this is something that can be also solved with Robot -

Related

How do I access an alert on a new window when the window hasn't loaded anything yet?

I'm running a Selenium script and at one point, we have a new window open and before anything in the window loads, an alert pops up. We switch to the new window and attempt to confirm the alert. This is the same kind of alert we see in other places, but when we try to confirm, or even just try to get the alert object itself, the script hangs, trying to forward getAlertText for the next 10 minutes.
Finally it fails:
[1568822219.289][SEVERE]: Timed out receiving message from renderer: 600.000
...which is no surprise. What I don't understand is why we can't get the alert, which looks the same as every other alert I've ever handled through Chrome and Selenium, and why it doesn't return a NoSuchAlertException instead of very-slowly failing. I cannot inspect the alert through the developer tools and it doesn't register as a window:
We're using driver.switchTo().alert(). I've also used the ExpectedConditions.alertIsPresent() condition. I've even tried accessing the alert before switching to the new window, which I had no real hopes of working, but when you have nothing logical left you try the illogical stuff.
Has anyone else had this issue? What did you do to overcome it? Thanks!
This alert cannot be handled using selenium to handle it you can use sikuli
same I have handled using sikuli
just import sikuli package and write code
String dir = System.getProperty("user.dir");
String allow = dir+"/extra/allow.png";
Screen s = new Screen();
Pattern allowimg = new Pattern(allow);
System.out.println("Trying to click on Allow popup...");
Thread.sleep(2000);
s.click(allowimg);

Context-right click save link as

Using Java and Selenium, I am trying to get this link:
So from what I found, first I do a
Actions action = new Actions(driver);
scrollToElement(href);
action.contextClick(href).perform()
which brings up the menu, as it should. But then I do
action.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).build().perform();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
action.sendKeys(Keys.RETURN).build().perform();
However, that seems to do an arrow down OUTSIDE of the context menu.
This is a PDF link, so instead of selecting "Save link as", it hits the down arrow OUTSIDE of the context menu, so it closes the context menu, and just left-clicks on the pdf href.
So I am wondering about somehow having it move the arrow down while still in the context box. Or is there an xpath for "Save link as..."? I can't do an inspect on it. I suppose, I could try a
//*[contains(text(), 'Save link as"')]
but not sure that will work or not? Has anyone had this situation?
You're looking into wrong direction, you should not be automating file downloads as you're not testing your application, you're testing the browser and my expectation is that it is not something you should be doing.
Moreover, when you run your test remotely, i.e. in Selenium Grid or locally in parallel mode you will face issues as the browser which is not currently in focus will send key events to the application which is in focus.
The best option is extracting link href attribute value and performing the download using OkHttp library which is under the hood of Selenium Java Client. The relevant code would be something like:
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(href.getAttribute("href")).build();
Response response = client.newCall(request).execute();
File downloadedLogo = new File("myfile.pdf");
BufferedSink sink = Okio.buffer(Okio.sink(downloadedLogo));
sink.writeAll(Objects.requireNonNull(response.body()).source());
sink.close();

Selenium Java Client is not getting back the control once driver.get(URL) method is invoked

driver.get("MyURL");
System.out.println("URL is opened");
executeAutoItScript(scriptFileLocation);
when i open the URL i get an Authentication Required pop up.
To handle that I am using AutoIt script. But the problem is As soon as the first command
(driver.get("MyURL");)
is executed, Chrome will get open and the
Authentication pop up appears. And i have observed that the second line
System.out.println("URL is opened");
is not being executed. I debugged it and observed that the
control is not given to next line from
driver.get("MyURL");
and it hangs
there. I changed driver.get("MyURL"); to driver.navigate().to("MyURL"); but
there is no luck. Could anyone please help me to resolve this. Attached is
the pop up screenshot.
As per your code trials and the browser snapshot, it seems that the Browser Client (i.e. the Google Chrome Browser) is not returning back the control to the WebDriver instance and subsequently Selenium Java Client can't achieve the state of 'document.readyState' equal to "complete". Hence neither your next line of code:
System.out.println("URL is opened");
is getting executed, nor the AutoIt Script in next line:
executeAutoItScript(scriptFileLocation);
Solution
It is not clear from your question about the source of this Authentication Popup. Perhaps following the discussion Selenium - Basic Authentication via url you can pass the username and password being embedded within the URL as follows:
driver.get("http://admin:admin123#MyURL");
From: http://selenium-python.readthedocs.io/navigating.html
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
So, in this case your webpage is not fully loaded since it requires authentication. Here is what you can do
driver.get("MyURL");
executeAutoItScript(scriptFileLocation);
Thread.sleep(2000);// to wait for autoit script, you can also use other wait explicit wait
//Assert statement
System.out.println("URL is opened");
->First define the page load time for the driver.
->By using try-catch time out exception invoke the url.
->After that use robot class key events or key events class to enter the authentication details
Try the below one if any queries do lemme know:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
try{
driver.navigate().to("yourURL");
}
catch(TimeoutException te){
System.out.println(te);
System.out.println("Line went to Upto that Link");
after this you could proceed with the authentication pop-up code.
Do lemme know if you have any queries.
This helped me:
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("initialBrowserUrl", "about:blank");
options.setPageLoadStrategy(PageLoadStrategy.NONE);
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get(url);
//execute AutoItScript goes here

Selenium interacting with authentication popup

I have searched for this issue, and nothing that I've seen seems to work. I am currently trying to enter a username and password into an authentication box in Chrome, and I can't find a good way to do it in Selenium. The problem comes from the fact that running the "click" method on a webelement in Selenium effectively stops all execution until the authentication box has been dealt with. I've tried three approaches:
Before clicking on a webelement, create a new thread. In that thread, run
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Then run alert.authenticateUsing(new UserAndPassword("-ssqatest", "Sqa7-3$t"));
The problem with this is that alertIsPresent doesn't actually work in Chrome. I can confirm this by putting a print statement right after it, and it will never run, as it throws the error "cannot determine loading status". It works in Firefox, however, which leads me to the second attempt:
Doing it the same way as above, but in Firefox
This doesn't work because while the alert is detected properly, the line right after to authenticateUsing throws a selenium.Unsupportedcommandexception.
Directly typing in "https://username:password#url.com" into the Firefox browser after detecting the alert
This doesn't work because I can't use Selenium to get the URL of the page, since the webdriver was instantiated on the original thread, which got stopped during the authentication popup. I would prefer not to re-instantiate a new session just to get the URL of the page.
At this point, the only other method I can think of is to use java's Robot class, but I also would prefer not to do this, as it becomes quite messy with needing to manually have the robot have a keypress and keyrelease for each character.
What would be the best approach?
Thanks
You dont need to re-instantiate the thread. Unless im missing something you can go with #3 and just use switchTo() to change windows. Something like this:
Set<String> windowHandles = driver.getWindowHandles();
for(String handle : windowHandles) {
driver.switchTo().window(handle);
if(driver.getTitle().equals(NEW_WINDOW_TITLE)) {
return;
}
}

Handling alerts using HtmlUnitDriver in Java

I want to handle alerts Using HTMLUnitDriver in java. I am using following code to handle the alerts using firefox driver and it is working fine.
Alert alert = driver.switchTo().alert();
alert.accept();
but HTMLUnitDriver is giving error like
java.lang.UnsupportedOperationException: alert()
How to handle there alert box ?
If you don't need to check whether the alert actually appears, I would recommend changing the behavior of the JavaScript alert() method to log a message instead:
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
javascriptExecutor.executeScript("window.alert = function(message){ console.log(message); };" +
"window.confirm = function(message){ console.log(message); return true; };");
Then you can skip HtmlUnitDriver.switchTo().alert().accept() in your code.
Note: This method won't work if the alert appears on the initial page load since Selenium waits for the page to be loaded before interacting with it. So the above JavaScript will be executed too late.
As of HtmlUnitDriver version 2.25, HtmlUnitDriver.switchTo().alert().accept() no longer throws an UnsupportedOperationException(). However, accept() appears to do nothing except confirm that the alert is present. Since the alert cannot be dismissed, turning off alerts using the above method is probably the best/only solution. If you must test alerts with HtmlUnitDriver, you may need two separate tests---one for checking that the alert appears and another for checking that the browser behaves correctly when the alert is disabled.
If you desperately need alert handing and you are okay with building from source, alert handling has been implemented in the master branch of HtmlUnitDriver. I'm not sure when it will be included in a release, though.
The request to implement the alert-API in the HTMLUnitDriver has been placed several years ago. This is the link:
https://code.google.com/p/selenium/issues/detail?id=1105&q=alert%28%29&colspec=ID%20Stars%20Type%20Status%20Priority%20Milestone%20Owner%20Summary
As this seems to be a hard nut to crack, you have to think about some tricks to circumvent the modal dialogs (alert, confirm, ...) in JavaScript. At least until they have implemented the alert-API.
The tricks to prevent the modal dialogs to show consists of adding additional JavaScript to your Selenium script. For example change the callback-functions to avoid the alert box.
Also, be aware it is impossible to close/cancel/confirm modal dialogs with JavaScript itself. That's the reason why you should prevent them to show. This is due to security reasons.
Until the alert-API has been implemented, this is the only way to handle it with HtmlUnitDriver.

Categories

Resources