Search code examples
c#seleniumselenium-webdrivertouchgeckodriver

How to simulate touch / tap on Selenium Firefox C#


I'm trying to simulate tap on screen on Selenium WebDriver Firefox (Geckodriver).

There is a script writes if you have clicked (by mouse) or tapped to screen. I can "click" on it by Selenium without any problem. I just want to "tap" it. Is it possible? How can i do it?

I'm using latest versions of Geckodriver and Firefox. My codes are below.

var touchActions = new OpenQA.Selenium.Interactions.TouchActions(driver);
string url = "https://jsfiddle.net/bkwb0qen/15/embedded/result/";
driver.Navigate().GoToUrl(url);
driver.SwitchTo().Frame(0);
IWebElement element = driver.FindElement(By.Id("square"));
touchActions.SingleTap(element).Build().Perform();


Solution

  • Selenium isn't great for testing mobile, so if you need to do much more than just the tap, I would suggest finding another tool such as Selendroid. I tested your code using TouchActions and couldn't get the event to fire on the test site you have provided. I got the event to register by using a custom JavaScript script:

    string url = "https://jsfiddle.net/bkwb0qen/15/embedded/result/";
    driver.Navigate().GoToUrl(url);
    driver.SwitchTo().Frame(0);
    IWebElement element = driver.FindElement(By.Id("square"));
    
    StringBuilder str = new StringBuilder();
    str.Append("var target = document.getElementById('square');");
    str.Append("const touch = new Touch({");
    str.Append("identifier: \"123\",");
    str.Append("target: target,");
    str.Append("});");
    str.Append("const touchEvent = new TouchEvent(\"touchstart\", {");
    str.Append("touches: [touch],");
    str.Append("view: window,");
    str.Append("cancelable: true,");
    str.Append("bubbles: true,");
    str.Append("});");
    str.Append("target.dispatchEvent(touchEvent);");
    
    ((IJavaScriptExecutor)driver).ExecuteScript(str.ToString());
    

    From doing a bit of research though I doubt this would be very reliable if you need to run it on a myriad of sites. I have tested this with ChromeDriver and GeckoDriver, on both the desktop site and mobile site. Hope this helps.