How to press shift + ctrl + s in Selenium ?
I have used the code below:
Actions action = new Actions(driver);
action.sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s")).perform();
its Throwing error
If you simply send a series of keys, then Webdriver for each keycode first press a given key, then depress it.
So your code sendKeys(Keys.chord(Keys.SHIFT + Keys.CONTROL + "s") is equivalent to the below series of events in the time:
Press SHIFT
Depress SHIFT
Press CONTROL
Depress CONTROL
Press s
Depress s
This is not what you want, because you are excpecting that Ctrl and Shift have been pressed and are held at the moment of time when the S key is pressed.
You need to use Actions#keyDown method to press the key and leave it in the pressed state, and later Actions#keyUp to release the key. So the sequence of actions might be:
Press SHIFT - using keyDown
Press Ctrl - using keyDown
Press then release S (this key can be pressed and immediately released using sendKeys method)
Wait for an visible effect of pressing Ctrl-Shift-S
Release Ctrl - using keyUp
Release Shift - using keyUp
Points 5 and 6 (releasing keys) must be done in order to avoid unexpected effects later in the test code (don't leave Ctrl+Shift in a pressed state).
Here is a link to simple page on jsfiddle which help us to test our WebDriver code.
<body>
<p>Press a key on the keyboard in the input field to find out if the Ctrl-SHIFT key was pressed or not.</p>
<input id="ctrl_shift_s" type="text" onkeydown="isKeyPressed(event)">
<p id="demo"></p>
<script>
function isKeyPressed(event) {
console.log( event.keyCode);
var x = document.getElementById("demo");
if (event.shiftKey && event.ctrlKey && event.keyCode == 83 ) {
x.innerHTML = "The Ctrl-SHIFT-S keys were pressed!";
} else {
x.innerHTML = "Please press Ctrl-SHIFT-S";
}
}
</script>
</body>
If you move a cursor to INPUT field on this page (id="ctrl_shift_s" of this element), and then press Ctrl-SHIFT-S keys (holding SHIFT and Ctrl), then a message will appear The Ctrl-SHIFT-S keys were pressed!
Below is an example (working) code tested agaist the above test page using latest IE,Firefox and Chrome drivers. You must use requireWindowFocus(); option in order to run Actions in IE driver.
WebDriver driver= null;
try{
System.setProperty("webdriver.ie.driver", "C:\\instalki\\IEDriverServer.exe");
System.setProperty("webdriver.chrome.driver", "C:\\instalki\\chromedriver.exe");
System.setProperty("webdriver.gecko.driver", "C:\\instalki\\geckodriver.exe");
InternetExplorerOptions opt = new InternetExplorerOptions();
opt.requireWindowFocus();
// driver=new InternetExplorerDriver(opt);
// driver = new ChromeDriver();
driver = new FirefoxDriver();
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait( driver, 10);
driver.get("https://jsfiddle.net/39850x27/2/");
final By inputField = By.id("ctrl_shift_s");
final By messageWeWaitFor = By.xpath("//*[text() = 'The Ctrl-SHIFT-S keys were pressed!' ]");
final By frame = By.name("result");
// Swift to a frame (our test page is within this frame)
driver.switchTo().frame(driver.findElement(frame));
// move a corsor to the field
wait.until(ExpectedConditions.elementToBeClickable(inputField)).click();
Actions a = new Actions(driver);
// Press SHIFT-CTRL-S
a.keyDown(Keys.SHIFT)
.keyDown(Keys.CONTROL)
.sendKeys("s")
.build()
.perform();
//Wait for a message
wait.until(ExpectedConditions.visibilityOfElementLocated(messageWeWaitFor));
System.err.println("Success - Ctrl-Shift-S were pressed !!!");
// Sleep some time (to see the message is really on the page)
Thread.sleep(5000);
// Release SHIFT+CTRL keys
a.keyUp(Keys.CONTROL)
.keyUp(Keys.SHIFT)
.build()
.perform();
}finally {
if(driver!=null) {
driver.quit();
}
}
Related
After clicking the create invoice button, it opens a new tab and redirects you to it. Next, it should click a button but it says no element exists. Did it search the element on the current page ? not on the new tab?
Tried explicit wait for that button and tried switching back and forth to the tab
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
String newUrl1 = driver.getCurrentUrl();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
#Test (priority=4)
public void ClickInvoice() {
}
#Test (priority=5)
public void test() {
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
}
Expect to click button after redirecting.
First of all wait for 2nd window to open and be available to the WebDriver. You can use Explicit Wait for this like:
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(2));
Check out How to use Selenium to test web applications using AJAX technology article for more information on the concept
Once you have the confidence that the number of windows is 2 you can use switchTo().window() function to change the context for the 2nd window:
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));
When you are clicking on new button, new tab is getting open. In this scenario, you need to use WindowsHandles. Try below code:
#Test (priority=3)
public void ProductListExpress() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase.php");
Set<String> winHandles= driver.getWindowHandles();
Iterator<String> it = winHandles.iterator();
String parentWindowId = it.next();
String newWindowID= it.next();//Here you will get windows id of newly opened tab
driver.switchTo().window(newWindowID); //now your driver is switching to new tab
String newUrl1 = driver.getCurrentURL();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase page ");
}
else {
System.out.println("Failed in proceeding to Purchase page");
}
}
You can switch to new tab with this way :
//Click create invoice button
driver.findElement(By.name("btncreateinvoice")).click();
System.out.println("Successful in clicking create invoice");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
during execution whenever a new tab or window opens, control of the driver still remains in the original tab or window unless we write couple of lines of code to manually switch the control to new tab or window.
In your case, Since the driver control is still in original tab and next element to click is in new tab, selenium is not able to find it, hence it says no element exists
#Test (priority=5)
public void test() {
WebDriverWait w= new WebDriverWait(driver, 10);
ArrayList<String> x = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(x.get(1)); // here x.get(1) indicates that
driver control is switched to new tab or new window
w.until(ExpectedConditions.elementToBeClickable("locator of button to be clicked"));
}
In case ,in your next steps if you can to continue execution in the original window or tab, you have to again switch selenium driver control back .
driver.switchTo().window(x.get(0));// during next steps if you want
driver control to switch back to original tab or window you have to write this line
of code
IDK if this is what you're asking, but it might be. I was CTRL+CLICKING a button to open a new tab. This is how I found the tab:
Set<String> curWindows = new HashSet<> (driver.getWindowHandles ());
String newWindowHandle = null;
a.keyDown(Keys.LEFT_CONTROL).click(THE_BUTTON).keyUp(Keys.LEFT_CONTROL).build().perform();
this.delay (500);
for (String windowHandle : driver.getWindowHandles ()) {
if (curWindows.contains (windowHandle) == false) {
newWindowHandle = windowHandle;
break;
}
}
if (newWindowHandle == null) {
log.error ("Unable to find the new window handle.");
return null;
}
Issue:
I am using IE11 with Selenium Webdriver, When I try to close the IE browser, I get a "Message From WebPage" popup display, I am trying to click "OK" but Alert handle does not work, It doesn't click "OK".
Selenium version: 3.12.0
IEDriverServer (32bit) version: 3.12.0
public void selectReqFolder() throws Exception {
windowHandle = new WindowsHandle();
//Clicking here open new child window
driver.findElement(Contract_File_Action_Copy_Frwd_Trnsction_button_Solcitation_Link).click();
//Window handle method, switch focus on to child window and does all the task in there
windowHandle.windowsHandle();
//Using window handles to switch to parent window
Set<String> s1 = driver.getWindowHandles();
// Now we will iterate using Iterator to go over the totoal windows
Iterator<String> I1 = s1.iterator();
// List of the windows
String parent = I1.next();
String child_window = I1.next();
**[![// Here we will compare if parent window
driver.switchTo().window(parent);
//Closing the broswer
driver.close();
Thread.sleep(4000);
//Handeling Alert
Alert alert = driver.switchTo().alert();
// Capturing alert message.
String alertMessage= driver.switchTo().alert().getText();
//To click on OK button of the alert
driver.switchTo().alert().accept();][1]][1]**
}
I'm having problems automating tests on an internal website. In some cases, a popup will freeze the test until I manually close the popup. After the popup is opened, no code is run, not even System.out.println's.
driver.findElement(By.id("top_toolbarSALTkA7_Aras_Tbi_promote")).click();
System.out.println("test");
I have tried multiple ways of handling the popup, but no code at all is run after the click(), and it seems it never times out.
Tried:
1.
((JavascriptExecutor) driver).executeScript("return document.getElementById('top_toolbarSALTkA7_Aras_Tbi_promote', 'onClick')");
2.
Set<String> windowHandles = driver.getWindowHandles();
for(String handle : windowHandles)
{
driver.switchTo().window(handle);
if (driver.getTitle().contains(title))
{
System.out.println("- (Page title is: " + driver.getTitle() + ")");
break;
}
}
3.
driver.switchTo().alert();
4.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
If I close the popup, the test will continue with the System.out.println and then continue until finshed.
I'm using Selenium Webdriver 2.48.2 with FireFox 31.0, programming is Java. Any ideas what can be done? (It's not possible to change the website)
Finally found the solution!!! Found it in the Selenium official user group: https://groups.google.com/forum/#!searchin/selenium-users/popup%7Csort:relevance/selenium-users/eDqPiYoJ9-Q/kRI67cCVe5wJ
Solution is to start a new thread that waits a couple of seconds, and then presses enter (or in my case first tabs to the "OK" button). Just call the function before the popup is opened.
public static final void prepareToPressEnterKey(int seconds, int tabs) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
for (int i=0; i<tabs; i++)
{
robot.keyPress(KeyEvent.VK_TAB);
TimeUnit.SECONDS.sleep(1);
robot.keyRelease(KeyEvent.VK_TAB);
}
robot.keyPress(KeyEvent.VK_ENTER);
TimeUnit.SECONDS.sleep(1); //press for 1 sec
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException | InterruptedException e) {
System.out.println("Prepare to Press Enter Exception");
}
}
},
seconds,
TimeUnit.SECONDS);
scheduledExecutorService.shutdown();
}
Still, if there are any better solutions I'd very much like to know. Thanks!
Just disable popup. I mean you need to call the next script inside the current browser context (executeScript - I guess in your, Java binding case):
document.alert = window.alert = alert = () => {};
I am trying to move slider using drag and drop. It identifies the element and clicked on it and after that nothing happens and my code stuck there itself(like waiting for user input). As soon as i moved my mouse little bit manually it executes rest of the code and works as expected. please help me what is this weird behavior.?. below is the code i used to build drag and drop.
Actions builder = new Actions(driver);
Action secondSlide = builder.dragAndDropBy(secondSlider, 50, 0).click().build();
System.out.println("waiting");
secondSlide.perform();
System.out.println("not waiting");
"Waiting" message is printing nicely but it doesn't print "not waiting" as it stuck in "secondSlide.perform()" line. But as soon as i moves my mouse little bit manually it prints "not waiting" and program ends gracefully.
Try to do it differently. Here is a number of approaches:
WebElement element = driver.findElement(By.name("element dom name"));
WebElement target = driver.findElement(By.name("target dom name"));
(new Actions(driver)).dragAndDrop(element, target).perform();
Or:
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
I'm facing this issue since some days now but didn't manage to overcome it trying different ideas.
Problem description: I wanna select a line in a table (GWT CellTable), perform some actions (which are my application specific) on it and then unselect back the line.
The line never gets unselected.
I'm quite new to selenium And I don't know if someone else has run into same problem and if there is a workaround to it. Thanks in advance
Code:
#Test
#SuppressWarnings("serial")
public void testClearEventCodes(){
refreshBrowser();
testWEHSearch();
WebContext faresContext = rootContext.gotoId(Strings.WEH_FARES_TABLE);
//INITIALLY HOT AND EVENT FARE
assertTrue("Y N N N N".equals(faresContext.gotoTableCell(1, 15).getText()));
assertTrue("CHINAYEAR".equals(faresContext.gotoTableCell(1, 16).getText()));
checkColorCodes(new HashMap<String, String[]>(){
{
put(getFareKey("GMP", "PAR", "KE", "0004", "K001", "OW", "Public"), new String[]{"1", COLOR_CODE_HOT_AND_EVENT_FARE});
}
});
faresContext.gotoTableRow(1).getElementWebContext(1).click();
rootContext.gotoId(Strings.WEH_CLEAR_EVENT_CODES_BUTTON).click();
faresContext.gotoTableRow(1).getElementWebContext(1).ctrlClick();
//ENSURE ALL EVENT CODES ARE CLEARED
assertTrue("".equals(faresContext.gotoTableCell(1, 16).getText()));
checkColorCodes(new HashMap<String, String[]>(){
{
put(getFareKey("GMP", "PAR", "KE", "0004", "K001", "OW", "Public"), new String[]{"1", COLOR_CODE_HOT_FARE});
}
});
}
And bellow is the method to CTRL CLICK the line:
/**
* Holds Control key and Clicks on current element.
*/
public void ctrlClick() {
Actions actionBuilder = new Actions(driver);
actionBuilder.keyDown(Keys.CONTROL).click(getSingleElement()).keyUp(Keys.CONTROL);
org.openqa.selenium.interactions.Action action = actionBuilder.build();
action.perform();
}
Your problem might be related to the new Firefox feature in which display settings are now taken into account. You can try changing the display settings for your computer to 100% and try again.
https://code.google.com/p/selenium/issues/detail?id=6774