JS get svg object inside embed

370 Views Asked by At

I've got some simple html like below, and I need to access the SVG object in a JS script, and I'm having a horrible time of it.

<!DOCTYPE html>
<html>

  <head>
    <script src="../dist/svg-pan-zoom.js"></script>
  </head>

  <body>
    <h1>Demo for svg-pan-zoom: SVG in HTML 'object' element</h1>
    <object id="demo-tiger" type="image/svg+xml" data="tiger.svg" style="width: 500px; height: 500px; border:1px solid black; ">Your browser does not support SVG</object>

    <script>
      // Don't use window.onLoad like this in production, because it can only listen to one function.
      window.onload = function() {
        svgPanZoom('#demo-tiger', {
          zoomEnabled: true,
          controlIconsEnabled: true
        });
      };
    </script>

  </body>

</html>

Once this page loads, there is a new document with an svg tag within the object. I can select the object tag with document.querySelector("#demo-tiger"), that seems to work fine, but absoultely cannot get to the svg within it. i've tried contentDocument and getSVGDocument() and everything else i could think of. They all turn up null.

Any guidance would be greatly appriciated.

1

There are 1 best solutions below

0
On BEST ANSWER

Unfortunately, this will not work if you load it locally through file://. This is because the contentDocument attribute is only accessible when both frames (main/top and the loaded one) are SameOrigin and the rules for file: uri's are stricter than normal urls for security reasons. You can find more information on this here: What is the Same-Origin Policy for File URIs?