instead of sendkeys last copied item from clipboard is getting entered in the element - selenium

In my application I have an email field and I'm using sendkeys to send an email address, but instead of sendkeys selenium inserts the value from clipboard. Do anyone faced this issue?
code:
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
since Id is dynamic I have taken xpath from parent container

In Node.js javascript, on hungarian keyboard, the # sign in sendKeys has replaced with the content of clipboard. If you try to replace "#" width its unicode value "\u0040", the result is same, the sendKeys has has replaced with the content of clipboard, even though try to the tricky Key.chord( Key.ALT, "v", Key.NULL ) form, it does nothing.
// if clipboard contains XXX
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
// result: field content is sampleXXXsample.com
If you put # sign on the clipboard, it works well, but you cant guarantee the content of clipboard in test automation. There is a way, to send keys to the active item.
I would avoid to fill the field with javascript, as mentioned above, because javascript fill it directly, does not care with the field status, fill it with value even though the field is inactive, do not triggers events, etc, javascript is brute force fill the field.
Send. Keys. There is a npm package for it. It is a wrapper for powershell sendkeys, so works only on windows.
npm install -g sendkeys
and the test code:
const sendkeys = require( 'sendkeys');
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample")
// result: cursor is in the field, field contains 'sample'
sendkeys.sync( "#sample.com" )
// result: field content is 'sample#sample.com'

If send keys is not working try using action chains. It is often a good way to solve selenium interaction problems.
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
email = driver.find_element_by_xpath("//div[#class='auth-container']//input[#type='text']"))
action.send_keys_to_element(email, "sample#sample.com").perform()
hope this helps

I am run script in java, hope this help you..
Using javascript I successfully send data into textbox.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('identifierId').value='admin'");
Another way :-
WebElement Username = driver.findElement(By.xpath("//*[#id=\"identifierId\"]"));
((JavascriptExecutor)driver).executeAsyncScript("arguments[0].value='admin'",Username);
Here we are passing WebElement as a argument to the javaScript.
For more information refer this link
Another way is using robot class ..Common solution is to use the clipboard, Copy text and paste that text into text field.
String username = "admin";
StringSelection stringSelection = new StringSelection(username);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.
String un="admin";
char c;
int l=un.length(),v1=0,v2=0;
//System.out.println(l);
while(v1<l)
{
c=un.charAt(v1);
v2=(int) c; //converts character to Unicode.
robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(v2));
Thread.sleep(150);
robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(v2));
v1++;
}
see it works perfectly and it's awesome! Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.

I have encountered this, but it seemed to be intermittent. The code that was working well for months, suddenly doing the same thing (pasting from clipboard in place of every # aka "at sign" ).
I was able to make it go away (won't say "fix") by updating Chromedriver. I suspect that this was because Chrome has auto-updated, but the Chromedriver didn't. Can't be sure, because also had to reboot in the process.
In any case, this is not "normal". Email addresses with # sign should be passed through sendKeys without problems.

This works for me:
chromeoptions.AddUserProfilePreference("settings.language.current_input_method", "US");

Related

Protractor sendKeys issue with scripted input fields

I'm automating e2e tests with Protractor on an angular app.
However, I have an issue when sending keys on input fields.
The sendKeys would miss few characters everytime so I found a workaround :
static sendKeys(value, element){
value.split('').forEach((c) => element.sendKeys(c));
}
This works well but it takes more than 3 times the time the original sendKeys function would.
Well no problem my tests are still functionnal right ?
My app now has new fields with scripts behind them.
One of them is a datepicker input, you can either choose from the datePicker or type it manually. However, for today's date you would type 09022018 and the slashes are automatically appended at the right place (like so 09/02/2018). If you were to enter a wrong date the field is cleared.
Now back to the problem : it seems that both my implementation of sendKeys and the original one loose focus after each submitted key. This means that I can't enter a valid date in the input field as it's cleared after each simulated keypress.
I could use browser.executeScript to fix it but I wouldn't be able to test the functionnality adding slashes. Also, as you type, the datepicker is still open and refreshes after each keypress, you can select a date from it at any time and that is also a feature I want to test.
Thanks in advance
Use executeScript to set the date in backgrond, then use sendKeys to enter a space or Tab at the end to trigger the Keyborad event which will check the input and format the input with slash
function enterDate(date) {
var script = 'arguments[0].value=arguments[1]';
// input box for date
var dateBox = element(by.xxx(yyy));
browser.executeScript(script, dateBox, date);
dateBox.sendKeys(" ");
// or try send Tab
dateBox.sendKeys(protractor.Key.TAB);
}
enterDate('09022018');
You can try this solution on other fields you fixed but take 3 more time.

Wrong text entered by sendkeys

I am trying to automate a webpage where i have to enter credit card details.
During manually entering CVV of the credit card I am able to move forward, but while entering value using sendkeys it throws an error.
driver.findElement(By.name("password_ccCvv")).click();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
I tried clicking on the textbox and then entered value. This also didn't work.
While entering value through send keys, i cant see what value is being sent because its encrypted.
If Webdriver is not able to enter data using standard way (using sendKeys method), you can use a workaround using JavaScriptExecuter, as shown below:
JavascriptExecutor e = (JavascriptExecutor)driver;
e.executeScript("arguments[0].setAttribute('value', arguments[1])", driver.findElement(By.name("password_ccCvv")), "999");
Let me know, whether it works for you.
Try this using javascriptexecuter and let me know
In Python
driver.execute_script("document.getElementById('password_ccCvv').value = '001';");
In Java
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('password_ccCvv').value = '001';");
If on text box already text is there first clear it using following:
driver.findElement(By.name("password_ccCvv")).clear();
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
Or try only this
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
while(driver.findElement(By.id("makePaymentButton")).isEnabled())
{
Thread.sleep(4000);
driver.findElement(By.name("password_ccCvv")).sendKeys("999");
Thread.sleep(4000);
driver.findElement(By.id("makePaymentButton")).click();
Thread.sleep(2000);
}
This is working for me. I am able to authenticate in 3rd or 4th try.
I erased my entered password and enter again, it works.

Selenium SendKeys not working for open brackets and harsh keys when using java

I have using selenium webdriver 2.33.0 and i have a requirement of sending data with the following characters inside the data ("(", "#")
When we tried to send these characters using sendkeys
"WebElement dat = driver.findElement(By.xpath("xpathexpression);
dat.sendkeys("select * from (?s, ?p, ?o)");
The following data gets displayed in the textarea as select * from ?s, ?p, ?o)
the open bracket is missing. I have used selenium actions class sendkeys and robot sendkeys also.
I am not able to fix the issue. Can someone help me on this?
Ugly but efficient workaround: replace the opening brackets ( with the key sequence shift + 9, as suggested by user2935099.
dat.sendKeys(Keys.chord(Keys.SHIFT, "9"));
Funnily, this seems to work regardless of your current keyboard layout (I use an Irish locale with a French layout).
I stumbled upon this one with version 2.40.0, and it is definitely a bug in Selenium. Using the following in the Firefox JavaScript console works flawlessly:
var box = getElementById('SearchBox');
box.setValue('AB (CDE FGH)');
The issue is resolved when using actions class
WebElement dat = driver.findElement(By.xpath("xpathexpression");
dat.click();
Actions data = new Actions(driver);
data.sendKeys(Keys.chord(Keys.CONTROL,"a"),Keys.DELETE);
data.perform();
query = query.replaceAll("\\(", Keys.chord(Keys.SHIFT,"9"));
query = query.replaceAll("\\#", Keys.chord(Keys.SHIFT,"3"));
query = query.replaceAll("\\-", Keys.SUBTRACT.toString());
query = query.replaceAll("\\}", Keys.chord(Keys.SHIFT,"]"));
data.sendKeys(query);
data.perform();
I tried entering the same thing with my selenium setup and it worked fine in both firefox and chrome. I am not not very sure about the reason but one thing that I can notice that you are using very old selenium version(2.33.0) currently 2.37.0 is available. May be you should try updating the selenium and t should work as expected.
Same problem here, using 2.40.0 my workaorund was using clipboard, not pretty but testsystems have not much use for a clipboard anyway...
public static void setTextByClipboard(WebElement element, String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
element.sendKeys(Keys.chord(Keys.CONTROL, "v"));
}

How to foucs a new window (third party without windowName) in selenium IDE?

I am submitting search criteria through form to third party URL. I tried to give target="someName". But when i am trying to focus on new window using "sameName" and validating some text there, selenium unable to find that locator or focus on that window. retuning false. please help on this. its urgent.
I also tried storeAllWindowNames or Ids selenium commands, also not working its returning main window ID instead of new open window.
the idea is in the following. as you try to validate some text in a new window, I do not see any necessity to get window name as you are able to get the xpath or cssselector of the text to be validated using firepath (firebug addon in ffox) and using command
String txt = driver.findElement(By.xpath(//...blablbalba)).getText().trim();
//or
String txt = driver.findElement(cssSelecot(html>..blalblabla...)).getText().trim();
//validation
Assert.assertTrue(txt.equals("blablabla"));
you can actually validate it.
or if you want to validate something and selenium is not able to cope with it then I recommend you to use js (getText using js):
String cssSelector=....
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\""+cssSelector+"\");");
stringBuilder.append("return x.text().toString();") ;
String res= (String) js.executeScript(stringBuilder.toString());
Assert.assertTrue(res.trim().contains("blablabla....") );
Hope this works for you.
This is the solution:
Well, if you have no choice but use it. Here is one solution:
if you have a target with your own name like target="popup", then you only need open the target window before click on the link. Example:
[b]store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"[/b]
If you have a target="_blank", you need change the target before open the window.
store "javascript{this.page().findElement('link=My link who open the popup with target blank').target='popup'}", "myVar"
store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"
Then, you click on the link and selectWindow("popup"). That is.
Another solution is rewrite the entire A tag and change the href/target by a javascript window.open but this is a litle more work to do.

How to verify a target="_blank" link using selenium?

Some links on our page open in a new window using target="_blank". How can I make selenium look at the right window so I can verify that the page is linking to the right page?
Here's what I've been trying:
open /page/
click link=Find us on Facebook!
pause 2000
selectWindow title=window title
verifyTextPresent some text
You don't need to pass a parameter to selectWindow. The browser will automatically give your new window focus, you just need to tell selenium that it's changed. Also make sure you give your new window enough time to actually load before verifying anything:
open /page
click link=Find us on Facebook!
pause 1000
selectWindow
verifyTextPresent some text
$this->click('css=.sf_admin_action_page:first a');
$this->waitForPopUp('_blank');
$this->selectWindow('_blank');
$this->waitForElementPresent('css=.t-info:contains(xxx2)');
// ps. selenium2
you should use selectPopUp to focus the new window. see its document:
selectPopUp:
Arguments:
windowID - an identifier for the popup window, which can take on a number of different meanings
Simplifies the process of selecting a popup window (and does not offer functionality beyond what selectWindow() already provides).
If windowID is either not specified, or specified as "null", the first non-top window is selected. The top window is the one that would be selected by selectWindow() without providing a windowID . This should not be used when more than one popup window is in play.
Otherwise, the window will be looked up considering windowID as the following in order: 1) the "name" of the window, as specified to window.open(); 2) a javascript variable which is a reference to a window; and 3) the title of the window. This is the same ordered lookup performed by selectWindow .
I took slightly different approach which was to force any links to use target = _self so that they could be tested in the same window :
protected void testTextLink(WebDriver driver, final String linkText, final String targetPageTitle, final String targetPagePath) {
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement link = driver.findElement(By.linkText(linkText));
// ensure that link always opens in the current window
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('target', arguments[1]);", link, "_self");
link.click();
wait.until(ExpectedConditions.titleIs(targetPageTitle));
// check the target page has the expected title
assertEquals(driver.getTitle(), targetPageTitle);
// check the target page has path
assertTrue(driver.getCurrentUrl().contains(targetPagePath));
}
Simply use this code.
public void newtab(){
System.setProperty("webdriver.chrome.driver", "E:\\eclipse\\chromeDriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.w3schools.com/tags/att_a_target.asp");
//I have provided a sample link. Make sure that you have provided the correct link in the above line.
driver.findElement(By.className("tryitbtn")).click();
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")), Keys.NUMPAD2).build().perform();
// In keyboard we will press
//ctrl+1 for 1st tab
//ctrl+2 for 2nd tab
//ctrl+3 for 3rd tab.
//Same action is written in the above code.
}
//Now you can verify the text by using testNG
Assert.assertTrue(condition);
In this Case we can use KeyPress
keyPress(locator, keySequence)
Arguments:
locator - an element locator
keySequence - Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". [Give for CTRL+T]
Simulates a user pressing and releasing a key.