Mary
Mary

Reputation: 11

Capture contentDocument for svg object in selenium

I'm trying to automate test for svg images which is rendered in a web application.

The html looks like-

<object class="svgcanvas" type="image/svg+xml" data="test.svg"><h4>Error     loading SVG file</h4>
   #document
    <svg xmlns="http://www.w3.org/2000/svg"     xmlns:xlink="http://www.w3.org/1999/xlink" -webkit-user-drag: none; -webkit-tap-    highlight-color: rgba(0, 0, 0, 0);" viewBox="0 0 1188 840" xml:space="preserve">
      <rect x="0" y="0" width="1188" height="840" style="stroke:none;     fill:white"/>
      <circle cx="20" cy="830" r="0.144857" style="stroke:#E50033; stroke-    width:0.339429"/>
      <g id="XMP_1" style="stroke:#000000; stroke-width:0.339429">
        <path d="M554 401L641 401" style="stroke:#0000FF; stroke-dasharray: 3.5640  3.5640  3.5640  3.5640"/>
      </g>
</object>

I tried to get the svg object using the below code but svgElement throws the following error:

'((OpenQA.Selenium.Remote.RemoteWebElement)svgElement).Displayed' threw an exception of type 'OpenQA.Selenium.StaleElementReferenceException'

IWebElement objectTag =  _webDriver.FindElement(By.CssSelector("object.svgcanvas"));
IJavaScriptExecutor js = (IJavaScriptExecutor)_webDriver;
string findingSVG = "return arguments[0].contentDocument;";
var svgElement = js.ExecuteScript(findingSVG, objectTag);

So, is there a way to test page that have SVG embedded in the object tag?

Any help much appreciated.

Upvotes: 1

Views: 851

Answers (1)

Moshisho
Moshisho

Reputation: 2981

Your code tries to get the contentDocument for the <object> tag which returns a Document object from a frame, so it's not supposed to work.

The <object> tag is probably inside a <frame> so try switching to the content in the frame that contains the <svg> and then find your element:

_webDriver.SwitchTo().DefaultContent();
_webDriver.switchTo().Frame("YourFrameName");

IWebElement svgElementInsideFrame =  _webDriver.FindElement(By.TagName("svg"));

Upvotes: 1

Related Questions