Unable to fetch URL of window containing an alert box while using selenium webdriver - selenium

I am using selenium webdriver + java + eclipse + testng for my automation scripts.
I am trying to get the URL of window which contains an alert box.
On clicking download button on a webpage, it opens an alert box in a new window. I want to fetch the URL of this window.
I tried getCurrentURL command for this but i am getting UnhandledAlertException : Modal dialog present. If i dismiss the alert box the window containing is immediately closed so it is not possible to get the URL.
It seems the alert box (modal dialog here) is blocking webdriver in reading the URL of the window.
Please suggest me a solution for this.
Thanks

I'm not sure I understand the question as an alert box does not have any URL !
Anyhow, you can access it this way : Alert alert = webDriver.switchTo().alert();
You can then retrive the text content or interact with it as described in here : http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/Alert.html

I think you need to get the set of windowHandles first for this driver.getWindowHandles();. Then get the required Handle of the newly opened window by iterating them. After that you can switch to the opened window using driver.switchTo().window("pass the handle here");
Now your control comes to new window. Then use like driver.getCurrentUrl();
Hope this could help you. Best Regards :)

Related

Unable to switch among the windows

I am automating using selenium 2.0, my application launches the login page by default in a new window, hence my application has by default two windows. These two windows will remain open always. In this case I could switch between the windows without any problem. The below code is executed without any errors.
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
The problem starts while clicking the menu options a pop up window launches to search the records. Here, I need to switch between these three windows. I tried the below piece of code. It returns only the first two window handles.
Set availableWindows = driver.getWindowHandles();
This popup window is coded in such a way that, "In a .jsp file it is parameterised as window.open()".
Please let me know, if some one could help me on this?
If you're only seeing 2 window in getWindowHandles(), then the popup is probably a iframe. In this event, use driver.switchTo().frame() to switch focus to that frame instead of looking for an entirely new window.
Here's the documentation on the switch method: http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebDriver.html#switchTo()
One probable solution is to use JavascriptExecutor.executeScript() method to run a javascript code and handle the pop up window without switching into pop up window.
For example, from parent window of pop up window, run a javascript code which is something like this.
JavascriptExecutor exec = (JavascriptExecutor)driver;exec.executeScript("var popup = <<popupopener function>>; //operate on popup object to manipulate the markup of pop up window");

Selenium Webdriver 2.30 unable to identify object on the standard Salesforce lookup pop-up window

I am using Selenium Webdriver to automate functional TC in Salesforce application.
Test Scenario:
- On a case page, clicking the "Lookup" i.e., search icon opens up standard Salesforce search popup. I need to input specific string to the search field and click "Go" button.
Although I am able to click on the Search button, the script fails to identify any field on the popup.
I used Alert(), getWindowHandle & iterator functions to verify if the driver is working on the popup window. Yes it is.. the popup is is the working window. I could able to confirm this using the Java id for the browser window. But still it fails to identify any fields.
Let me know if any of you faces similar issue and any solution.
Do let me know if you like to have access to my working sandbox. Would be able to manage it.
Thanks, Manju
I believe the problem is that the elements inside the popup window are in a frame. After switching to the new popup window you need to switch to the frame first before being able to access any of those elements using:
WebElement frameLocator = driver.findElement(By.id("searchFrame"));
driver.switchTo.frame(frameLocator);
Further to Bob's answer you'll also then need to switch to the "resultsFrame" in order to use any of the links returned by the search. Note that in order to switch to a sibling frame you must first go up to the parent of the frameset using:
driver.switchTo().defaultContent();
(frameset guidance here: http://darrellgrainger.blogspot.co.uk/2012/04/frames-and-webdriver.html)
With Selenium IDE:
I was able to select the Salesforce PopUP with this code:
Command:selectPopUp
Target:
Value: Your popUp title
And the result frame:
Command:selectFrame
Target: name=resultFrame
Value:

Selenium WebDriver how to close browser popup

I am writing tests for a web App using selenium webDriver and came across a scenario where when I try to close the browser I get a popup saying "Are you sure? The page is asking you to confirm that you want to leave - data entered will be lost." with 2 buttons: Leave Page and Stay on Page
How do I click on those buttons?
( ( JavascriptExecutor ) _driver )
.executeScript( "window.onbeforeunload = function(e){};" );
solved the issue for me
IAlert alert = driver.SwitchTo().Alert();
alert.Accept(); //for two buttons, choose the affirmative one
// or
alert.Dismiss(); //to cancel the affirmative decision, i.e., pop up will be dismissed and no action will take place
You can interact with alerts and the like using the Alert API. Switching to the alert and confirm it would look like this (in Java):
Alert alert = driver.switchTo().alert();
alert.accept();
This is also explained in the Selenium FAQ.
def close_all_popups(driver):
driver.window_handles
for h in driver.window_handles[1:]:
driver.switch_to_window(h)
driver.close()
driver.switch_to_window(driver.window_handles[0])
You might try using keyboard events. So once the window pops up:
Tab onto the "Ok" button.
driver.Keyboard.PressKey(Keys.Tab);
You'll have to play around to see how many tab presses are required.
Then hit space.
driver.Keyboard.PressKey(Keys.Space);
Yeah it's sort of a hack, but WebDriver is still pretty immature.
EDIT: This will work for "real" popups, but as another answerer said, maybe not for weird in-page things. Basically, if you can tab to the close button manually, this method should work.
Not sure what is the structure of the popup that you have used.
Here are a few that may work for you if you have used either of as to popup.
If its an alert. you can try:
driver.SwitchTo().Alert()
If its a window that pops up then:
driver.SwitchTo().Window(<windowname>)
For iFrame:
driver.SwitchTo().Frame("iFrmLinks")
Once you get through either of the three then you can access all its internal elements.
Regards
Tahir
I've got the same problem when i have the form of fields and "done editing" submit button, because when Selenium IDE auto-click the javascript function, that responsible to disable confirmation window (leave page or still on it), it does not take "mouseup" mouse event that mean window.confirm still works and auto-pass test was fails. My solution is override javascript function window.onbeforeunload in this case (no need to ask if we know that we do when we record test in Selenium IDE). You can run override script in the Selnium IDE before click on "Save" (or something like this) button through selenium.runScript - it should simple disable the confirmation window.
Command: runScript
Target: {window.onbeforeunload=function(e){};}
You need to handle the unexpected alerts using try catch blocks. Put your code in try block and catch the 'UnhandledAlertException'
Example:
try{
.....
.....
code here
}catch(UnhandledAlertException e ){
driver.switchto().alert().dismiss();
}
Put one of these before the click event:
selenium.chooseCancelOnNextConfirmation()
selenium.chooseOkOnNextConfirmation()

Selenium popup support

Please give me an example java code to open a popup and move RC control to popup.
is there any way to come back on main window after checking some element on popup window.
I have few questions on this as selenium always need windowid to get control over popup.
1-What is the best way to get the windowid of any popup.
2-Should i have to search it in view sources of base page.
3-is it necessary that we must get the windowid of the each & every popup in the view source of the page. if not so what will be work-around.
4-Is window id present in any java-script function? if so ,there is one example
I didn’t get Window id of popup
script language="javascript"
begin
function popup(){
window.open('URL/to/popup.html','PopupName','toolbar=0,location=0,
status=0,menubar=0,scrollbars=0,resizable=0,width=345,height=400');
}
// end
/script
This will definitely help you. Handling Popups
Hope this helps

Click in OK button inside an Alert (Selenium IDE)

I need to click the 'Ok' button inside an alert window with a Selenium command. I've tried assertAlert or verifyAlert but they don't do what I want.
It's possible the click the 'Ok' button? If so, can someone provide me an example of the Selenium IDE command?
Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:
Popup Dialogs
Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:
Java
Alert alert = driver.switchTo().alert();
Ruby
driver.switch_to.alert
This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.
To click the "ok" button in an alert box:
driver.switchTo().alert().accept();
This is an answer from 2012, the question if from 2009, but people still look at it and there's only one correct (use WebDriver) and one almost useful (but not good enough) answer.
If you're using Selenium RC and can actually see an alert dialog, then it can't be done. Selenium should handle it for you. But, as stated in Selenium documentation:
Selenium tries to conceal those dialogs from you (by replacing
window.alert, window.confirm and window.prompt) so they won’t stop the
execution of your page. If you’re seeing an alert pop-up, it’s
probably because it fired during the page load process, which is
usually too early for us to protect the page.
It is a known limitation of Selenium RC (and, therefore, Selenium IDE, too) and one of the reasons why Selenium 2 (WebDriver) was developed. If you want to handle onload JS alerts, you need to use WebDriver alert handling.
That said, you can use Robot or selenium.keyPressNative() to fill in any text and press Enter and confirm the dialog blindly. It's not the cleanest way, but it could work. You won't be able to get the alert message, however.
Robot has all the useful keys mapped to constants, so that will be easy. With keyPressNative(), you want to use 10 as value for pressing Enter or 27 for Esc since it works with ASCII codes.
1| Print Alert popup text and close -I
Alert alert = driver.switchTo().alert();
System.out.println(closeAlertAndGetItsText());
2| Print Alert popup text and close -II
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()); //Print Alert popup
alert.accept(); //Close Alert popup
3| Assert Alert popup text and close
Alert alert = driver.switchTo().alert();
assertEquals("Expected Value", closeAlertAndGetItsText());
If you using selenium IDE then you have to click on Ok button manually because when alert message command run that time browser stop working and if you want to click on ok button automatically then you have to use selenium RC or webdriver and below command is for Selenium IDE
In selenium ide use storeeval command, different type of boxes
storeEval | alert("This is alert box") |
storeEval | prompt("This is prompt box. Please enter the value") | text
storeEval | confirm("this is cofirm box") |
You might look into chooseOkOnNextConfirmation, although that should probably be the default behavior if I read the docs correctly.
The question isn't clear - is this for an alert on page load? You shouldn't see any alert dialogues when using Selenium, as it replaces alert() with its own version which just captures the message given for verification.
Selenium doesn't support alert() on page load, as it needs to patch the function in the window under test with its own version.
If you can't get rid of onload alerts from the application under test, you should look into using GUI automation to click the popups which are generated, e.g. AutoIT if you're on Windows.
Use the Alert Interface, First switchTo() to alert and then either use accept() to click on OK or use dismiss() to CANCEL it
Alert alert_box = driver.switchTo().alert();
alert_box.accept();
or
Alert alert_box = driver.switchTo().alert();
alert_box.dismiss();
about Selenium IDE, I am not an expert but you have to add the line "choose ok on next confirmation" before the event which trigger the alert/confirm dialog box as you can see into this screenshot:
assertAlert ought to do the trick. I see in the docs that alerts generated in a page's OnLoad event handler cannot be scripted this way (and have experienced it myself, alas, due to the ASP.NET page lifecycle). Could that be what you're running into?
For selenium, an alert is the one which raised using javascript e.g.
javascript:alert();
There is one basic check to verify whether your alert is actually a javascript alert or just a div-based box for displaying some message.
If its a javascript alert, you wont be able to see it on screen while running the selenium script.
If you are able to see it, then you need to get the locator of the ok button of the alert and use selenium.click(locator) to dismiss the alert. Can help you better if you can provide more context:
IDE or RC?
HTML code of the alert
your selenium script.
Vamyip
Use chooseOkOnNextConfirmation() to dismiss the alert and getAlert() to verify that it has been shown (and optionally grab its text for verification).
selenium.chooseOkOnNextConfirmation(); // prepares Selenium to handle next alert
selenium.click(locator);
String alertText = selenium.getAlert(); // verifies that alert was shown
assertEquals("This is a popup window", alertText);
...
This is Pythoncode
Problem with alert boxes (especially sweet-alerts is that they have a
delay and Selenium is pretty much too fast)
An Option that worked for me is:
while True:
try:
driver.find_element_by_xpath('//div[#class="sweet-alert showSweetAlert visible"]')
break
except:
wait = WebDriverWait(driver, 1000)
confirm_button = driver.find_element_by_xpath('//button[#class="confirm"]')
confirm_button.click()
The new Selenium IDE (released in 2019) has a much broader API and new documentation.
I believe this is the command you'll want to try:
webdriver choose ok on visible confirmation
Described at:
https://www.seleniumhq.org/selenium-ide/docs/en/api/commands/#webdriver-choose-ok-on-visible-confirmation
There are other alert-related API calls; just search that page for alert