Access parent DOM through script in embedded SVG

Discuss SVG code, accessible via the XML Editor.
coiner
Posts: 19
Joined: Mon Mar 14, 2011 5:21 pm
Location: NY

Access parent DOM through script in embedded SVG

Postby coiner » Wed Sep 07, 2011 1:08 am

I am working on an SVG web application that I am embedding into an HTML5 page. The SVG doc has its own script that performs operations on the entire page. For the sake of example, I will show what I would like to accomplish using the HTML5 <audio> tag. Interacting with this element is cake if I embed the SVG doc directly into the HTML of the page, it's as simple as accessing the DOM through JavaScript. However, I would like to get this app to a point where it is placed into the page with an <embed> tag.

I know that an embedded Flash/AS can access the page's DOM through the ExternalInterface class so I would imagine there is a way to do so using pure JavaScript as well. The embedded SVG will always be on the same domain so there should not be any security issues. Any help with finding a solution to this would be appreciated.

Here is some code to show what I mean (I have left out namespaces and such to simplify):

The SVG:

Code: Select all

<svg>
  <script type="text/javascript">
    //the audio element on the page
    var audio = document.getElementById('theAudio');

    //a function to instruct the audio element to play
    function playAudio() {
      audio.play();
    }
  </script>
 
  <!-- A button to play the audio when clicked -->
  <rect x="0" y="0" width="50px" height="50px" fill="black" onclick="playAudio()" />
</svg>


The HTML:

Code: Select all

<div>
  <!-- The embedded SVG doc -->
  <embed src="play_audio.svg" type="image/svg+xml" />
</div>

<!-- The Audio element -->
<audio id="theAudio" src="sound.wav" preload="auto">
  Your browser does not support HTML5 audio.
</audio>


coiner
Posts: 19
Joined: Mon Mar 14, 2011 5:21 pm
Location: NY

Re: Access parent DOM through script in embedded SVG

Postby coiner » Wed Sep 07, 2011 3:31 am

Well it turns out that the solution to this was so simple that I'm ashamed I posted this :oops: I'm sure that the specificity of this post will help someone though.

So to access the parent html DOM from a script within an embedded SVG document, all you have to do is get the window's parent like so:

Code: Select all

var parentDocument = window.parent.document;

cluesome
Posts: 8
Joined: Thu Sep 16, 2010 11:59 pm

Re: Access parent DOM through script in embedded SVG

Postby cluesome » Tue Mar 20, 2012 9:35 am

It helped me; thanks.


Return to “SVG / XML Code”