Draw on a Canvas Using Selenium - selenium-webdriver

I'm using selenium with java (latest for both). Trying to draw on a small canvas area inside a modal in our webapp. The library we used for our canvas was 'signature pad js'. I have confirmed it is not inside an iframe or anything tricky that could be the problem (it's just a regular div.modal-body with a div.signature-input canvas element).
But it is not doing anything. Have looked at many posts here on stackoverflow and most of them seem pretty identical with few variations to try (I've been trying them all).
Here's the latest code I tried:
// Draw a signature of some sort
WebElement element = driver.findElement(Using.locator(SIGNATURE_AREA)); // canvas element
Actions builder = new Actions(driver);
builder.clickAndHold(element).moveByOffset(10, 50).
moveByOffset(50,10).
moveByOffset(-10,-50).
moveByOffset(-50,-10).release().perform();
I've tried all sorts of offsets, and such to no avail.
If anyone has experience with this, would really love a hand.

I think your issue is in the code , I've done this with ruby and it worked fine.. Code in Ruby below (worked in FireFox)
driver.find_element(:xpath, "html/body/div[1]/div[5]/div[2]/canvas").click
element = driver.find_element(:xpath, "html/body/div[1]/div[5]/div[2]/canvas");
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(150, 50).click.perform
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(100, 50).click.perform
driver.action.move_to(element).perform
driver.action.click_and_hold(element).perform
driver.action.move_by(300, 10).click.perform
sleep (5)
So I have tried same thing using Java for you , and its working fine , Its drawing two lines as expected. The trick is that moveby should not be followed with a click otherwise it will loose focus. Below code is working fine in java and chrome . I used https://sketchtoy.com/ to draw on canvas
public class BrowserTesting {
WebDriver driver;
#Test
public void test1() throws InterruptedException {
//WebDriverManager.chromedriver().setup();
System.setProperty("webdriver.chrome.driver","C:\\Users\\pathtyourchrome\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
//disable automation info bar
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.get("https://sketchtoy.com/");
WebElement element = driver.findElement(By.xpath("//div[#class='sketch-canvas-container']/canvas"));//canvas element
Actions builder = new Actions(driver);
builder.moveToElement(element).perform();
builder.clickAndHold(element).perform();
builder.moveByOffset(150, 50).perform();
builder.moveToElement(element).perform();
builder.clickAndHold(element).perform();
builder.moveByOffset(100, 50).perform();
builder.moveToElement(element).perform();
Thread.sleep(5000);
//driver.quit();
}
}
See this screen shot for the drawing:
Let me know if this worked!

Related

Element is not clickable at point ... error when using headless browsing

I have this error "org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (209, 760)", when I run the piece of code below in headless mode. When it is run with browser displayed I have no error and test passes fine. As you can see below, I trie with waiting, js executor, actions move to element but still no good result. I am using xpath to locate / define the element, and not coordinates. Why is this happening please and how can I solve it? Thanks in advance.
#Test(priority = 1)
public void verifyAddUserWithMarkedMandatoryFields() {
// accessing add user webpage / functionality
userListObject.getAddUserButton().click();
// inserting data to complete form
addOrEditUserPageObject.insertCredentials(userModel.getUsername(), userModel.getEmail(), "", userModel.getPassword());
// clicking Submit when becoming enabled
WebDriverWait myWaitVariable = new WebDriverWait(driver, 5);
myWaitVariable.until(ExpectedConditions.elementToBeClickable(addOrEditUserPageObject.getSubmitButtonAddOrEdit()));
// Actions actions = new Actions(driver);
// actions.moveToElement(addOrEditUserPageObject.getSubmitButtonAddOrEdit()).click().perform();
JavascriptExecutor jse = (JavascriptExecutor)driver;
// jse.executeScript("scroll(209, 760)"); // if the element is on top.
jse.executeScript("scroll(760, 209)"); // if the element is on bottom.
addOrEditUserPageObject.getSubmitButtonAddOrEdit().click();
}
You should add screen size for the headless mode, something like this:
Map<String,String> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadsPath); // Bypass default download directory in Chrome
prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
ChromeOptions opts = new ChromeOptions();
opts.setExperimentalOption("prefs", prefs);
opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage");
driver = new ChromeDriver(opts);
I put much more things here, the only relevant point here is "--window-size=1920,1080", this should resolve your problem.
The rest is to show how things are managed, including other relevant settings for headless mode.

Selenium Web-Driver Popup

I am unable to write on this popup message using selenium.
Please feel free to help me in this case.
My Code is:-
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "F:\\gecko_driver\\geckodriver-
v0.16.1-win64\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("https://www.heycare.com");
driver.findElement(By.xpath("html/body/div[2]/header/div/nav/div/a")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("hello world-----1");
driver.switchTo().frame(0);
driver.findElement(By.id("mobile")).sendKeys("7015273543");
System.out.println("hello world-----2");
//Driver.findElement(By.id("mobile")).sendKeys("7015273543");
driver.findElement(By.id("Pass")).sendKeys("123456");
}
Error:-
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: *[name='mobile']
Code is working fine till:-
driver.findElement(By.xpath("html/body/div[2]/header/div/nav/div/a")).click();
Unable to write on that popup form that comes after clicking on the login button..
I navigated to that website and successfully targetted the mobile number field using this css selector #mobile which targets the id attribute. You're doing this for your password field. Try having your test use this:
Driver.findElement(By.id("mobile")).sendKeys("7015273543");
See if that helps...
Edit: I'm not sure that the unformatted code block you're showing that switches frames is necessary. Unless you're working with iframes, I didn't see any in the minute I was looking around.
Edit2:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.heycare.com");
System.out.println("hello world");
driver.findElement(By.className("log-pop")).click();
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.name("mobile")));
driver.findElement(By.name("mobile")).sendKeys("7015273543");
driver.findElement(By.id("Pass")).sendKeys("123456");
You could try something like this, I added in a call to WebDriverWait to account for the possible delay between clicking the login button, and waiting for the login prompt popup to finish it's animation prior to be allowed to be clicked. I'm not sure if this will work in your case, but it's a possibility I sniffed out when I was observing the site's behavior.
(I didn't test any of this code, it's freehand written. So take it with a grain of salt. It might not work flawlessly as is.
Bit of java nit, you should make your object references lowercase, save capitalized symbols for class names. I had a moment of trying to figure out why you were calling static methods of a class called Driver instead of an instance of the class WebDriver

How to Test Print-preview of Chrome browser using Chrome webdriver?

I have tried using switching between windows using
String winHandleBefore = driver.getWindowHandle();
<code to print>
for (String winHandle : driver.getWindowHandles())
driver.switchTo().window(winHandle);
driver.findElement(By.className("cancel")).click();
driver.switchTo().window(winHandleBefore);
This hangs my test case execution after it opens the print preview page.
Also tried with javascript executor method, but no use.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.close()", "");
Please suggest if it's possible to do so.
I have found the answer to my question. I used below code snippet.
//Create a Region for Desktop Screen
ScreenRegion s = new DesktopScreenRegion();
//Find target with below Image in Desktop Screen
Target target = new ImageTarget(new File("Image.png"));
ScreenRegion r = s.find(target);
// Create a mouse object
Mouse mouse = new DesktopMouse();
// Use the mouse object to click on the center of the target region
mouse.click(r.getCenter());
With the help of this snippet you would able to find the print or cancel and do the mouse click event and proceed with selenium tests. This was possible using sikuli API

How to take full page screen shot in internet explorer using selenium webdrivers

I am not able to take the whole page screen shot using selenium webdriver.I am using internet explorer.
I tried robot function of java using mouse roll button but failed.
Please try the following let me know if it works for you
WebDriver driver = new FirefoxDriver();
driver.get("http://www.somewebsite.com/");
File imgFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(imgFile , new File("c:\\tmp\\test.png"));
if i have misunderstood you que please let me know
If the above answer fails, you can give a try making using of Augemented WebDriver, which can be used with IEDriver on it's latest version, try following code
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenFile.getAbsolutePath(), new File("c:\\tmp\\test.png"));
You can also get screenshot in the form of bytes, by switching the OutputType as required
.getScreenshotAs(OutputType.BYTES)

Selenium Webdriver drag and drop NOT working in Chrome

I used the below code for drag and drop. It worked in Firefoxdriver but NOT in chromedriver.
WebElement dragElement = driver.findElement(By.id(dragid1));
WebElement dropElement = driver.findElement(By.id(dropid1));
Actions builder = new Actions(driver);
Action drag = builder.clickAndHold(dragElement).build();
drag.perform();
Action move = builder.moveByOffset(355, -20).build();
move.perform();
TimeUnit.SECONDS.sleep(2);
Actions release = builder.clickAndHold(dropElement).release();
release.perform();
Please Help!
If you have both source and target IDs, then why don't you try to use drag and drop?
I'm not very good with Java, but here's how I've done it in Python. I hope it helps you a bit.
from selenium.webdriver.common.action_chains import ActionChains
actionChains = ActionChains(driver)
actionChains.drag_and_drop(dragElement, dropElement).perform()
Tried below sample code with chromedriver:2.15, chrome:v43 and is working fine with Chrome.
Sample Code:
System.setProperty("webdriver.chrome.driver","drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(1,TimeUnit.MINUTES);
driver.get("http://jqueryui.com/droppable");
driver.switchTo().frame(0);
WebElement dragElement = driver.findElement(By.id("draggable"));
WebElement dropElement = driver.findElement(By.id("droppable"));
Actions builder = new Actions(driver);
builder.clickAndHold(dragElement).moveToElement(dropElement).release().build().perform();
Try bundling all those seperate Action objects into a single Actions object
Actions act = new Actions(driver);
act.ClickAndHold(dragElement );
act.MoveToElement(dropElement );
act.Release(dragElement );
act.Build().Perform();
Note: For me, in Chrome & IE, sometimes just dragging to an Element was not enough to make it stick there, and I would have to add in an extra act.MoveByOffset(0, 5); before releasing to move just a few pixels, which seems to work
Is there a reason you have to wait for 2 seconds before releasing, or is that just what worked in FF?
I had the same problem but got to override it like this:
//Setup robot
Robot robot = new Robot();
robot.setAutoDelay(50);
//Maximized browser:
robot.keyPress(KeyEvent.VK_F11);
Thread.sleep(2000);
WebElement dragElement = driver.findElement(drag_element);
Actions builder = new Actions(driver);
builder.dragAndDropBy(dragElement,0, 200).build().perform();

Resources