Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Drag and drop not working in Chrome or Firefox

I use the Drag and drop code below to drag a picture in to a photofield. This works fine in InternetExplorer, but doesn't work in Firefox or Chrome. I don't understand why not.

As you can see in the code below I've tried a lot of different ways to do the drag and drop, but none of them works. The main problem is that the target is not updated after releasing the image. I see the drop happen but no update.

Does anyone have any idea why this is? I'm using C# and the latest Selenium driver 2.39, chrome driver 2.8.

public static void DoDragAndDrop(IWebDriver driver, string dragImageId, string dropFieldId)
    {
        Console.WriteLine("Drag and drop image '{0}' to the editor {1}..", dragImageId, dropFieldId);
        IWebElement dragElement = WebDriverExtensions.TryFindElement(By.Id(dragImageId));
        IWebElement dropElement = WebDriverExtensions.TryFindElement(By.Id(dropFieldId));

        if(dragElement == null)
            Console.WriteLine("dragElement is null");
        if(dropElement == null)
            Console.WriteLine("dropElement is null");

        ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView();", dragElement);
        Thread.Sleep(500);

        ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView();", dropElement);
        Thread.Sleep(200);

        Console.WriteLine("Drag and drop 1");
        var builder1 = new Actions(driver);
        builder1.MoveToElement(dragElement).ClickAndHold();
        builder1.MoveToElement(dropElement).Build().Perform();
        Thread.Sleep(2000);

        Console.WriteLine("Drag and drop 2");
        var builder2 = new Actions(driver);
        builder2.DragAndDrop(dragElement, dropElement);
        Thread.Sleep(2000);

        Console.WriteLine("Drag and drop 3");
        var builder3 = new Actions(driver);
        builder3.DragAndDrop(dragElement, dropElement).Build().Perform();
        IAction dragAndDrop = builder3.ClickAndHold(dragElement)
            .MoveToElement(dropElement)
            .Release(dropElement)
            .Build();
        dragAndDrop.Perform();
        Thread.Sleep(2000);


        Thread.Sleep(1000);
        Console.WriteLine("Drag and drop succeeded..");
    }
like image 603
PitAttack76 Avatar asked Sep 13 '25 16:09

PitAttack76


1 Answers

This is how I've got it working in FireFox now. Chrome still fails. The only difference is that I've added offsets in the MoveToElement method, as seen in The Rookies comment.

var builder = new Actions(driver);
        builder.ClickAndHold(dragElement);
        builder.MoveToElement(dropElement, 5, 5);
        builder.Perform();
        Thread.Sleep(250);
        builder.Release(dropElement);
        builder.Perform();
like image 194
PitAttack76 Avatar answered Sep 16 '25 05:09

PitAttack76