This is a very common issue with Selenium and SVG elements, because they are often special cases due to the way in which they render inside the DOM.
The `Actions` class of Selenium sometimes gets haywire with SVG elements because they don't quite act like regular HTML elements.
Here's how you might try to workaround this problem:
Solution 1: Click Using JavaScript
Instead of using `Actions` and right click on the element you can simulate a click on SVG directly using JavaScript. This usually helps in bypassing the mouse interaction problems of the SVG elements in Selenium.
WebElement mapObject = driver.findElement(By.xpath(\"//*[name()='svg']/*[name()='rect']\"));
//Click on the svg element using JavaScript
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true}));", mapObject);
Because SVG elements are in another XML namespace, you must use `//*[name()='rect']` so Selenium can find them. Sometimes you also need `getBoundingClientRect()` to get the element in the viewport when clicked.
WebElement mapObject = driver.findElement(By.xpath("//<.[CDATA[*[name()='svg']/*[name()='rect']]]>"));
Solution 3: `moveToElement` with Offset Click using `Actions`
At times, if the SVG is not scaled, then `moveToElement` with a small offset can be even more reliable to click on an SVG. Here is how you can try that too:
WebElement mapObject = driver.findElement(By.xpath("// ////*[@name()='svg']//*[@name()='rect'] \\\")); Actions actions = new Actions(driver);
// Move to the element with an offset and right-click actions.moveToElement(mapObject, 1, 1).contextClick().perform();
Explanation
- JavaScript Click: I never used the native click, because that would often reliably simulate a mouse event much better on the SVG
- Bounding Client Rect: The coordinates for the mouse event will then be more accurate, especially helpful where the item had been transformed in some fashion, such as scaled
- Move with Offset: In case the rectangle is very small, use an offset; it helps the driver see it.
This often solves issues with interaction between SVG elements with Selenium setups.