Daan Lambrechts
Daan Lambrechts

Reputation: 275

How can I send a variable from an embedded SVG to the HTML document?

I embedded a SVG into a HTML document using this code

<embed src="circle.svg" type="image/svg+xml" />

In the SVG file, I got a script block like this

<svg onload="myFunction()">
<script  type="text/javascript">
<![CDATA[
    function myFunction() {
        var sum;
        sum = 5 + 3;
    }
]]>
</script>
</svg>

How can I get the variable 'sum' from the SVG in the HTML document? (Note: The scripting in the SVG is a lot more complex than a simple sum, but I didn't want to overload this question with code)

Upvotes: 3

Views: 3782

Answers (3)

Haribabu
Haribabu

Reputation: 11

There is a work arround. I don't know how old this Question was, but someone will get use of it.


In the SVG file.

<svg onload="myFunction()">
<script  type="text/javascript">
<![CDATA[
    function myFunction() {
        var sum;
        sum = 5 + 3;
    }
    if(window.parent.svgLoaded) window.parent.svgLoaded(this);
]]>
</script>
</svg>

on the embeded HTML file.

<script>
    var svgScript;
    function svgLoaded(script){
        alert("gotcha!")
        svgScript = script;
    }
    function onPlayPause(){
        svgScript.myFunction();
    }
</script>

It works.

Upvotes: 1

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 60966

The answer is that you would do exactly as if the <embed> was an <iframe> and the document inside it was an HTML document.

You can pass data e.g via postMessage, or by using global variables or functions on the corresponding window object.

in the svg:

function foo() {
  var parentWindow = window.parent;
  parentWindow.someGlobalVar = 47;
}

Then you can read the someGlobalVar variable in the html main document. You can also call functions, as in this example.

Upvotes: 1

Jo&#227;o Pimentel
Jo&#227;o Pimentel

Reputation: 301

I don't think you can define javascript functions in SVG and call them (at least externally). However, you can probably achieve what you want by defining the function in the HTML file instead of in the SVG. For instance, if you want to count all rectangles in a given SVG, you can use a code as follows:

<embed id="mySVG" src="circle.svg" type="image/svg+xml" onload="countRectangles();"/>
<script>
  function countRectangles()
    {
      var svg = document.getElementById("mySVG").getSVGDocument();
      var allRectangles = svg.getElementsByTagName("rect");

      var result = allRectangles.length
      alert(result);
      return result;
    }
</script>

Upvotes: 0

Related Questions