Why drag and drop is not working in Selenium Webdriver?

后端 未结 12 1668
借酒劲吻你
借酒劲吻你 2021-01-11 11:45

I am trying to drag an element into another element using Selenium WebDriver but it\'s not working. I tried all the solutions which I can find on internet but none of the so

12条回答
  •  心在旅途
    2021-01-11 11:54

    I have also faced the same issue. Please find below custom java-script function for drag & drop.

    1) Create DragDrop.js file and paste below code in it

        function customEvent(typeOfEvent) {
        var event = document.createEvent("CustomEvent");
        event.initCustomEvent(typeOfEvent, true, true, null);
        event.dataTransfer = {
            data: {},
            setData: function (key, value) {
                this.data[key] = value;
            },
            getData: function (key) {
                return this.data[key];
            }
        };
        return event;
    }
    function dispatchEvent(element, event, transferData) {
        if (transferData !== undefined) {
            event.dataTransfer = transferData;
        }
        if (element.dispatchEvent) {
            element.dispatchEvent(event);
        } else if (element.fireEvent) {
            element.fireEvent("on" + event.type, event);
        }
    }
    function executeDrageAndDrop(element, target) {
        var dragStartEvent = customEvent('dragstart');
        dispatchEvent(element, dragStartEvent);
        var dropEvent = customEvent('drop');
        dispatchEvent(target, dropEvent, dragStartEvent.dataTransfer);
        var dragEndEvent = customEvent('dragend');
        dispatchEvent(element, dragEndEvent, dropEvent.dataTransfer);
    }
    

    2) Using below code we can call above custom function(Below is C# code)

    string script = System.IO.File.ReadAllText(@"{filepath of DragDrop.js file}");
    script = script + "executeDrageAndDrop(arguments[0], arguments[1])";
    IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
    
    IWebElement source = driver.findElement(By......);
    IWebElement target = driver.findElement(By......);
    
    executor.ExecuteScript(script, source, target);
    

提交回复
热议问题