How can I press the OK button in a JS alert programmatically?
What I want to do: every time after the alert is created, the OK button is pressed.
This is for
Using chooseOkOnNextConfirmation you can do that.
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);
For more information, go through this link link
Swift 3
you want to try this code in show alert and ok and cancel button
let sharephotoAction = UIAlertController.init(title: "Confirm Ticket", message:"Please Collect Your Ticket Before 1 Hours Ago in Location", preferredStyle: .alert )
sharephotoAction.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (alertAction) in
_ = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.Save), userInfo: nil, repeats: false)
}))
sharephotoAction.addAction(UIAlertAction(title: "Cancle", style: .default, handler:nil))
self.present(sharephotoAction, animated: true, completion:nil)
If you 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 catch 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.
You can use GSEvent.h for handling any type of keypress events, It is availble in GraphicsServices framework, It is private framewrk(so, you are not able submit it on appstore).
selenium.chooseOkOnNextConfirmation(); is working for me in Selenium RC.
We have to comment the code for Alert OK button then it will work.
If you can simulate a keypress of the space bar or enter key, then that will dismiss the alert. However you'd better be doing this from outside whatever makes the alert show up in the first place, since they tend to be blocking.
If this is JavaScript, you may be better off using console.log()
.