1

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.

SuperStew
  • 2,857
  • 2
  • 15
  • 27
  • Why do you need to access the svg- what exactly are you trying to do? – iPhoenix Dec 13 '19 at 22:39
  • @iPhoenix well trying to get this "pan and zoom" code to work that i found on github https://github.com/ariutta/svg-pan-zoom This is one of their demo files – SuperStew Dec 13 '19 at 23:04
  • Yes, but what are you trying to do? Does the library provide the methods for manipulating the svg for you? – iPhoenix Dec 13 '19 at 23:05
  • @iPhoenix the end goal is displaying an svg that can be interacted with, namely zooming in/out and panning around. the code on github is supposed to do exactly that. And it works for some other demo pages, but these have the svg defined directly in the html instead of embedded, which is not desirable – SuperStew Dec 13 '19 at 23:15
  • Is this what you are looking for? https://github.com/ariutta/svg-pan-zoom#embedding-remote-files – iPhoenix Dec 13 '19 at 23:18
  • @iPhoenix thats what i'm doing, yes, but it's not working. I'm running into errors in their code because `contentDocument` is always coming up `null`, so i'm looking to fix that – SuperStew Dec 13 '19 at 23:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204237/discussion-between-iphoenix-and-superstew). – iPhoenix Dec 13 '19 at 23:25

1 Answers1

2

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?

iPhoenix
  • 719
  • 7
  • 20