Unable to Automate Drag and Drop for IE11 : Selenium WebDriver - java

I am trying to automate drag and drop functionality in IE11 using Selenium Web Driver in Java. I am somehow able to achieve it on Chrome, but it's not happening in IE.
Before further explanation here is how I'm dragging and dropping:
Actions builder = new Actions(driver);
builder.clickAndHold(sourceElement)
.moveToElement(targetElement)
.release(targetElement)
.build().perform();
In IE: Instead of dragging and dropping it selects all the text from source to destination element. I thought this might be because it's pickup up the wrong element and tried the operation with some relevant parent and child elements but didn't work.
In Chrome: Works damn smooth.
In Firefox: Just performs click on holds and while dragging throws, element no longer attached to DOM exception. This might be because, I am dragging a row from a grid (kendo grid) and since dragging a row from a grid is not possible our devs have implemented it in such a way that when you drag a row a new dynamic element is created which moves along.
Just to add on more details:
I have already tried dragAndDrop() and other Javacript options.
I'm using the latest version of selenium and updated IE.
Our grid uses HTML5 components and I've discovered that there are few issues already there (not sure about what all issues though), but still since my scenario was working in one browser I hope this is not one of those issues.
I have made it possible somehow using Robot class but it is too unreliable and behaves weird, I would prefer giving up than using it.
Any help will be appreciated!

One solution if it's an HTML5 drag and drop is to simulate it with some javascript.
Here is a working example that drops an item to a bin:
final String JS_DnD =
"var src=arguments[0],tgt=arguments[1];var dataTransfer={dropEffe" +
"ct:'',effectAllowed:'all',files:[],items:{},types:[],setData:fun" +
"ction(format,data){this.items[format]=data;this.types.append(for" +
"mat);},getData:function(format){return this.items[format];},clea" +
"rData:function(format){}};var emit=function(event,target){var ev" +
"t=document.createEvent('Event');evt.initEvent(event,true,false);" +
"evt.dataTransfer=dataTransfer;target.dispatchEvent(evt);};emit('" +
"dragstart',src);emit('dragenter',tgt);emit('dragover',tgt);emit(" +
"'drop',tgt);emit('dragend',src);";
WebDriver driver = new InternetExplorerDriver();
driver.get("http://html5demos.com/drag");
WebElement ele_source = driver.findElement(By.id("two"));
WebElement ele_target = driver.findElement(By.id("bin"));
// drag and drop item two into the bin
((JavascriptExecutor)driver).executeScript(JS_DnD, ele_source, ele_target);

Related

Customize the browser icon when running a Selenium session?

I have some Selenium sessions where, if certain events occurs, I spawn a new browser and leave the old one as is so I later on can manually intervene. The problem is that it is hard to distinguish between such a deserted browser session and the one that is currently running.
Ideally I would like to add a badge to the browser icon that is displayed in the application switcher (cmd-tab) and the dock (but other solutions/suggestions are also welcome, like add something to the name of the browser). Is that possible?
Using Java on a Mac. A solution can be platform specific.
You can use below execute_script (This python code use java equalent)
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get(
"https://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page")
head = driver.find_element_by_tag_name("head")
link = driver.find_element_by_css_selector('link[rel="shortcut icon"]')
driver.execute_script('''var link = document.createElement("link");
link.setAttribute("rel", "icon");
link.setAttribute("type", "image/png");
link.setAttribute("href", "https://i.stack.imgur.com/uOtHF.png?s=64&g=1");
arguments[1].remove();
arguments[0].appendChild(link);
''',head,link)
time.sleep(70000)
you can use link element on head tag to add favicon. THe above code is an exaple where stackoverflow site will showup with my avatar
Output:
You should find the current link the website uses, remove it and replace it with your new link as shown in the code

Selenium Java Drag and Drop with HTML5

In several threads here, there is a work-around posted for selenium drag and drop with pages that use HTML5 for drag and drop. This work-around involves using javascript to simulate the drag and drop, for example Unable to perform HTML5 drag and drop using javascript for Selenium WebDriver test, and https://gist.github.com/rcorreia/2362544. This solution works well on this page, http://the-internet.herokuapp.com/drag_and_drop.
The general approach is to read the javascript file here (https://gist.github.com/rcorreia/2362544#file-drag_and_drop_helper-js) into a string, referred to as 'jsfile' below.
then in selenium (with java), pass in the css selectors for the source and the destination, where #column-a is the id of the source and #column-b is the target.
((JavascriptExecutor) driver).executeScript(jsfile +"$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});");
It works like a champ on that page.
However, a similar approach does not seem to work on this page, https://crossbrowsertesting.github.io/drag-and-drop.html. Nothing happens when I run
((JavascriptExecutor) driver).executeScript(jsfile +"$('#draggable').simulateDragDrop({ dropTarget: '#droppable'});");
I have pages that seem to behave like this second page (eg no drag and drop). As a first step in understanding this, I'd like to get an idea why this approach does not seem to work in the latter case here.
On re-testing https://crossbrowsertesting.github.io/drag-and-drop.html, it looks like the straight-forward use of the Actions class does the trick for drag and drop. In the particular app that I am testing, which is set up with some additional code to help with accessibility, I was able to get drag and drop happening by setting focus on the first element and hitting the return key, then setting the focus on the target element and hitting return again. I am fairly sure that this is custom event handling, so may not work in other applications. Just in case, I've posted code here which does this in selenium.
public void dndHtml5(String xPathSource, String xPathDestination) {
clickEnterKeyOnElement(xPathSource);
clickEnterKeyOnElement(xPathDestination);
}
public void clickEnterKeyOnElement(String xPath) {
setFocusOnElement(xPath);
WebElement target=element(xPath);
target.sendKeys(Keys.ENTER);
}
public void setFocusOnElement(String xPath) {
WebElement element = element(xPath);
Actions actions = new Actions(driver);
actions.moveToElement(element).build().perform();
}
public WebElement element(String xPath){
return driver.findElementByXPath(xPath);
}

Switching between tabs using webdriver in chrome

Am Opening a page performing some actions on that and i am using this piece of code to open another link in the next tab
String url = "https://qa.logfireapps.com/lgf_700_qa_rf";
String args1 = String.format("window.open('%s', '%s');", url, "new");
((JavascriptExecutor) driver).executeScript(args1);
Then i need to switch between this two tabs.
I used driver.switchTo.window(parentWin);
I also used this code
List windowHandles1 = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(windowHandles1.get(1));
Both of the cases did not work for me,but still the web driver code is running successfully without any errors even its not switching to first window.
I need to switch to the first tab,but all the actions are going on in the first tab but still in UI am seeing the second tab opened,It is not switching to the first tab but my whole webdriver code gets passed.
It is observed that switching problem happens only with this two sites
1) https://qa.logfireapps.com/lgf_700_qa/index/
2) https://qa.logfireapps.com/lgf_700_qa_rf
This was my solution to this using python. sorry no java example
def switch_to_new_window(driver, window):
driver.switch_to_window(driver.window_handles[window])

Cannot click element with IEDriverServer

I have an element on a web page that only becomes visible after clicking its parent element. So after clicking a demo in a list of demo's, a row of icons which represent actions for the selected demo is revealed. The following code works fine with both webdriver and chromedriver:
demo.click(); //click demo
waitForElementIsDisplayed(demoReservation_btn); //wait until reservation icon is displayed
demoReservation_btn.click(); //click icon
Originally i was getting a StaleElementReferenceException and i attempted to fix this by having a try/catch block within a while loop that would continue looping until the icon was clicked. This caused IEDriverServer to crash after a couple of loops.
I have also tried wrapping it up in an Action like so:
Action action = new Action(driver);
action.click(demo).click(demoReservation_btn).build().perform()
This results in a NoSuchElementException.
I know there are some problems mentioned in the documentation about browser focus and hovering over elements, but i dont believe this is the problem. I have tried a couple of other things like adding moverToElement to the action, hovering over the element but have had no success with these. I believe one possible solution is to use a javascript executor, but i would like to avoid this approach if possible, any other suggestions?
EDIT
IEDriverServer setup:
File file = new File("IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
return driver;
Try disabling Native events of IE
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability("nativeEvents",false);
driver = new InternetExplorerDriver(cap);
I had better result using that in C# version. Read this to learn why you may need to do this.

Can Selenium WebDriver open a link in a new tab from the current window [duplicate]

I want to be able to open a link in a new tab in Selenium 2. Also i want to close the tab when i am finished interacting with the page. How is this possible if I have a WebElement of an <a> tag?
I am using the Java API of Selenium 2 with the Firefox Driver, running on Firefox 4.
The way I figure out for selenium 2, work fine for Chrome and firefox, IE has security check issue:
Set<String> winSet = webDriver.getWindowHandles();
List<String> winList = new ArrayList<String>(winSet);
String newTab = winList.get(winList.size() - 1);
webDriver.close(); // close the original tab
webDriver.switchTo().window(newTab); // switch to new tab
At the moment, the Selenium WebDriver API doesn't have any way of handling tabs. The project would really need a consistent, cross-browser set of methods for managing tabs before I would expect to see an implementation in one of the language bindings like Java. Until then, your JavaScript solution may be the only way, and remember that your code would then be responsible for managing the lifetime of that tab.
to use selenium at its best we at sol-logics combine it with java.awt.robot class. you can send keys that can close a browser window. try using
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_W);
and reply if it works
Took awhile (~2 weeks) for me to track down the right sequence of commands, but this is by far the easiest method I've found for a Win7/Chrome setup to open a link in a new tab AND switch to the new tab automatically.
WARNING! Make sure to always perform the keyUp actions. If you fail to perform keyUp your system will keep those keys pressed until a reboot or keyUp occurs.
Windows 7/Chrome:
WebElement elem = driver.findElement(By.linkText("MyLinkText"));
// Chrome key combos:
// SHIFT + CTRL + click = Open in new tab (and switch to new tab)
// SHIFT + CTRL + RETURN = Open in new tab (in background)
Actions act = new Actions(driver);
act.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
// Wrap in a try/catch during implementation to ensure you perform keyUp(s).
elem.click();
act.keyUp(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
Note: I know it's an old thread, I just wanted to catalog the solution here because I couldn't find a more elegant solution and wanted to save someone else a little time (hopefully :).
Edit: Typo
Here is how i did it using Python.
This solution is a bit dirty but it works if you want to close the tab.
Im mimicking the mac shortcut CMD + W to close a tab, if you are running windows you may have to implement a different key combination.
import from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.amazon.com/gp/search/ref=sr_in_-2_p_lbr_brands_browse-_2895?rh=n%3A172282%2Cn%3A!493964%2Cn%3A502394%2Cp_lbr_brands_browse-bin%3ALytro")
action_chains = ActionChains(driver)
action_chains.key_down(Keys.COMMAND + "w")
action_chains.perform()
action_chains.key_up(Keys.COMMAND + "w")
driver.implicitly_wait(5)
What I use is the Robor class.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_W);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_W);
This makes the Robot rapidly press and release the CTRL + W keys to simulate a user interaction. If you only use keyPress event, this will close all the tabs and windows of the WebDriver.
Hope I helped you.

Categories