Highlighting an Element Using Selenium Webdriver at Specific Coordinates

I'm currently in the process of automating a web application built with HTML5 using Selenium Webdriver. I need help figuring out how to highlight the exact coordinates where I have clicked on the Canvas element. For example, if I click on the Canvas at coordinates 200,500, I want to be able to highlight just that point.

If I use JavaScript to highlight the element, it will highlight the entire Canvas element rather than the specific point I clicked on. Can anyone provide a solution for this? Thank you in advance.

My automation setup involves using specflow with C#.

Here is the code snippet for clicking on the Canvas at specific coordinates:

public void ClickCanvasElement(IWebDriver driver, By locator, int offsetX, int offsetY)
        {
            try
            {
                IWebElement element = FindElement(driver, locator);
                Actions actions = new Actions(driver);
                for (int i = 0; i < 10; i++)
                {
                    if ((element.Displayed == true && element.Enabled == true) || element == null)
                    {
                        actions.MoveToElement(element, offsetX, offsetY).Click().Perform();
                        break;
                    }
                    System.Threading.Thread.Sleep(500);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

Answer №1

If you want to implement highlighting of a specific element using JavaScript, try the following code snippet:

 public void HighlightElement(IWebDriver driver, By locator, int offsetX, int offsetY)
            {
                try
                {
                    IWebElement element = FindElement(driver, locator);
                    Actions actions = new Actions(driver);
                    for (int i = 0; i < 10; i++)
                    {
                        if ((element.Displayed == true && element.Enabled == true) || element == null)
                        {
                            actions.MoveToElement(element, offsetX, offsetY).Click().Perform();


    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

        js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element,"color: red; border: 3px solid red;");

                            break;
                        }
                        System.Threading.Thread.Sleep(500);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

Answer №2

In order to address this issue, one potential solution is to make modifications directly to the canvas itself. This could involve drawing a square or circle at specific coordinates (200,500) using context.fillRect. Here's an example of how you could implement this:

 IWebElement element = FindElement(driver, locator);
 IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

 js.ExecuteScript("var example = arguments[0]
                   var context = example.getContext('2d')
                   context.fillRect(200,500,10,10)",element);

It's important to note that this approach will only be effective if the provided coordinates align with the canvas coordinates. If not, a more complex method may need to be employed (additional guidance can be found here: http://javascript.info/coordinates)

  1. Locate the canvas element
  2. Determine the absolute coordinates of the located element
  3. Calculate relative coordinates
  4. Use JavaScript to generate a new shape on the canvas based on the initial point

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

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

Cookie for subdomain in Selenium

I am currently in the process of setting up some functional tests for a Django site that redirects users to dashboard.appname.com when they visit appname.com while already logged in. To enable this in the test environment, I must include a cookie in the b ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

Error in Selenium with Webdriver: displaying "null" in case of NoneType

I encountered an issue while attempting to crawl a bank website using the Google Chrome driver. Whenever the type is 'NoneType', I need the code to print 'null'. This code was written in Jupyter Notebook within Anaconda3. from bs4 impo ...

Remote control connections to the hub in Selenium Grid fail to register, yet the build is able to complete successfully

I have successfully set up a Selenium Grid on my local machine and then transitioned it to a server (Windows Server 2008 R2). The server instance is working well with locally launched agents, and the server's hosted console is visible over the intern ...

Getting the chosen option from a changing radio button

My radio button code looks like this: <span><input onClick="if (EventHandlers.valueChanged(event, this)==false) return false;" class="radio" label="Temp label" type="radio" id="TempId_01" onblur="EventHandlers.onBlur(event)" ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

Refreshing Javascript with AngularJS

I'm encountering an issue while starting my angular js application. On a html page, I have divs with icons and I want the background color to change on mouse over. This is working using jquery's $(document).ready(function(){ approach. The conten ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

retrieve JSON information using JSONP

Currently, I am working with a URL that returns data in JSON format. Here is the URL: http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=? When I enter this URL into a browser, it displays the following JSON re ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

What is the process for adding information to a MongoDB collection?

Working with NodeJS using Mongoose, I have defined two tables in db.js: const mongoose = require('mongoose') const UserSchema = new mongoose.Schema( { username: { type: String, required: true, unique: true }, email: { type ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

Creating Unique Numbers for Every <a> Element

Can someone help me figure out how to create a form that generates a unique set of random numbers from the range (0,9) displayed in a group of button tags? I've written some javascript code but it's not quite working as intended. (function($) ...