Using C# to simulate a mousewheel event on an IWebElement in Selenium

Description: An intricate arrangement of HTML rectangles displayed on the screen, each with a unique HTML id attribute making them selectable by Selenium IWebDriver and C# code without any overlaps.

Objective: My goal is to use Selenium and C# to programmatically create and trigger a mousewheel event (using IJavaScriptExecutor or other methods) on a specific rectangle element.

Inquiry: Can you provide guidance on how to accomplish this task? Thank you.

Answer №1

After thorough research, I have come up with this implementation:

//wheelTicks: negative for zoomin, positive to zoomout 
public object zoomElementById(string elemId, int wheelTicks=1)
{
     object response = null;

     string myCustomJavaScript =

            // Callback (must be placed first) used to notify the caller about async callee readiness
            "  var callback = arguments[arguments.length - 1];                                           " +
            "  var maxIntervals = arguments[1];                                                          " +
            //ms
            "  var intervalDuration = 150;                                                               " +
            "  console.log('executing javascript...', callback, arguments);                               " +

            "var d = new Date();                                                                         " +
            "var n = d.getTime();                                                                        " +

            "  var myZoomCenterElement = document.getElementById('" + elemId + "');                      " +
            // additional debug output in the console 
            "  console.log(myZoomCenterElement);                                                         " +

            // *** THE CORE OF THE SOLUTION *** Generates the WheelEvent object properly and triggers WheelEvent(Zoom)   
            "  var box = myZoomCenterElement.getBoundingClientRect();                                    " +    
            "  var boxMiddleX = Math.round((box.right + box.left )/2);                                   " +    
            "  var boxMiddleY = Math.round((box.bottom + box.top )/2);                                   " +
            "  var myWheelableElement = document.getElementsByClassName('svg-tree-view')[0];             " +
            "  var wheelEventInitDict = {                                                                " +
            "               'deltaX'    :      0.0,                                                      " +
            "               'deltaY'    :   -200.0,                                                      " +
            "               'deltaZ'    :      0.0,                                                      " +
            "               'deltaMode' :        0,                                                      " +
            "               'clientX'   :        boxMiddleX,                                             " +
            "               'clientY'   :        boxMiddleY                                              " +
            "               };                                                                           " +
            "  var myWheelEvent = new WheelEvent('wheel', wheelEventInitDict);                           " +
            "  console.log(wheelEventInitDict, boxMiddleX, boxMiddleY, myWheelEvent);                    " +

            " var myIntervalCounter = 0;                                                                 " +
            " var myInterval = setInterval(function(){                                                   " +
            "                    myWheelableElement.dispatchEvent(myWheelEvent);                         " +
            "                    myIntervalCounter++;                                                    " +
            "                    if (myIntervalCounter > maxIntervals) clearInterval(myInterval);        " +
            "                }, intervalDuration);                                                       " +

            " var sthToReturn = 'Returning: No request made!';                                           " +
            " var asyncAwaitInMiliSeconds = Math.ceil( 1.2 * intervalDuration * maxIntervals );          " +

            // Triggers the callback (to indicate async readiness) 
            " setTimeout( function(){                                                                    " +
            "                       console.log((new Date()).getTime()-n);                               " +
            "                       callback(sthToReturn);                                               " +
            "           }, asyncAwaitInMiliSeconds);                                                     " +

            ""
            ;
     _driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 20));

     IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
     try
     {
            // additional args(optional) to be sent to the JavaScript function are added after the first arg 
            return response = js.ExecuteAsyncScript(myCustomJavaScript, elemId, wheelTicks);

     }
     catch(UnhandledAlertException e)
     {
            Console.WriteLine("An Error Occurred! \n {0}", e.ToString() );
            return null;
     }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

AngularJS radio buttons can now be selected as multiple options

Currently, I am in the process of learning angular and have implemented a radio button feature in my program. However, I have encountered a perplexing issue that I cannot seem to explain. <!DOCTYPE html> <html> <head> <meta ch ...

What are some methods for extracting text from a document using Selenium Webdriver?

If I have a single document, how can I extract text from it using the Selenium WebDriver? Below is the code I've used: d1.findElementByClassName("odd").click(); Thread.sleep(5000); d1.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); WebElem ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

Angular view fails to update after form submission when using ngDialog to change the scope

After starting my Angular journey, I decided to challenge myself by creating a comprehensive todo app for educational purposes. I seem to be missing something pretty basic, although I can't quite put my finger on it. It seems like there might be an is ...

Is there a way to determine if a directory is empty using Node.js?

Quite a while back, I submitted a question related to PHP. Now I'm facing a similar situation with Node.js where the code below appears to be sluggish when used in a loop - is there a way to achieve this using only vanilla JavaScript in pure Node.js w ...

Can someone help me figure out the best way to locate a material-ui slider within a react

I am seeking to incorporate multiple material-ui sliders into a single react component that share a common event handler. However, I have encountered difficulties in identifying which slider triggered the event. Despite referring to the API documentation, ...

Show different options like selection menus, checkboxes, date pickers, and more based on the content of a JSON

Looking for Help with Dynamic Input Fields and Additional Elements I have successfully implemented dynamic input fields based on a JSON file, but now I need to include selections, checkboxes, and a datepicker as well according to their respective groups. ...

Storing a photo taken with a camera to a local directory on the computer

Currently, I am utilizing HTML5 inputs to capture a picture from the camera by using the code below: <input id="cameraInput" type="file" accept="image/*;capture=camera"></input> Subsequently, I am obtaining the image in blob format and manip ...

What is the best way to retrieve system information from a properties file and display it on a JSP page before the Javascript code is

As someone who is relatively new to JSPs and their capabilities, I am currently working on developing a suite of 4 separate webapp dashboards, each with its own standalone URL and index.(jsp|html) pages. The backend of these dashboards, which is written in ...

Error in Jquery validation caused by incorrect file extension type

Within my HTML form, I have multiple inputs set up for validation purposes: <form role="form" id="addForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="userName">U ...

Background image loading gets delayed causing it to flicker

Instead of having separate files for different elements on my site, I decided to keep all the JavaScript in one large file called my_scripts.js. To speed up loading times, I defer the loading of this file using inline JavaScript and make sure it is the las ...

Can Self-Invoking Functions, Resharper 6.1, and JS Lint all Play Nice Together?

Consider this piece of JavaScript code: MyCompany.MyProduct = {}; (function () { "use strict"; MyCompany.MyProduct.doSomethingAmazing = function () { }; }()); This approach is acceptable and passes Mr Crockford's JavaScript lint. Howe ...

Controlling the activation of a button on a parent modal popup from a child within an IFrame using javascript

I am struggling to toggle the button on the main window from the child window. Here is a snippet from the main page: <ajaxToolkit:ModalPopupExtender ID="mpeTest" runat="server" CancelControlID="btnClose" PopupControlID="pnl1" TargetControlID="showMp ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

Explore the new feature in React Vis LineMarkSeries where you can customize the style property to have distinct stroke and fill

In the component I have, the following code is included: <XYPlot height={300} width={500} xType="ordinal" yType="ordinal"> <XAxis /> <YAxis /> <LineMarkSeries data={data1} style={{line: {fill:"red"}, mark: {fill:"red", s ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Enhance Your Website with Bootstrap 3.0 Affix

Looking to attach a right hand column to the top of the window as you scroll using Bootstrap 3.0 and 'affix' feature. Here is the HTML for the element: <div class="col-lg-4 right-hand-bar" data-spy="affix" data-offset-top="477"> This is ...

The functionality of Selenium grid is dependent on having chromedriver locally installed

To set up my selenium grid and hub, I used the following commands: hub: java -jar selenium-server-standalone-3.14.0.jar -role hub node: java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://localhost:4444/grid/register After checking t ...