Venkatesh Laguduva
Venkatesh Laguduva

Reputation: 14348

How to share java script methods between html and svg?

I have got a html page embedded with a .svg. I have written most of the logic in java script and would like to share the same .js between html and .svg file:

for ex: I have got the following in mylogic.js:

var xmlDoc = null;
function loadXmlDoc() {
   xmlDoc = new XmlDoc.....
}

function onHtmlLoad() {
   loadXmlDoc();
}

function onSvgLoad() {
   xmlDoc.getElemementById(...
}`

and in the Html, I have got

<html>
<script src="mylogic.js"></script>
<body onLoad='onHtmlLoad();">
...
<object id='svgid' data='sample.svg'.../>
...
</body>
</html>

and the java script included in the html page is not visible in the embedded .svg file so I have to include them again like...

<svg...onload="window.onSvgLoad();">
<script xlink:href="mylogic.js></script>
</svg>

since I included the .js file twice, I am getting the xmlDoc as null inside onSvgLoad() function. I believe, there should be a way to get the same instance of xmlDoc loaded from html in svg. but I am not getting it..?

alternatively I tried not to include .js file in svg instead tried changing onload to onload="window.top.onSvgLoad();" ; then to onload="window.parent.onSvgLoad();" but still did not work! *Please note that I am using IE9 with its native support for Html5.

Upvotes: 0

Views: 217

Answers (1)

Robert Longson
Robert Longson

Reputation: 124016

javascript included in the html page IS visible from the embedded .svg file. Remove the script tag from the embedded svg and call the methods you want as parent.method e.g. if mylogic.js had

function hello()
{
    return "hello";
}

you could write

<script>
  alert(parent.hello());
</script>

in the embedded .svg file to call it.

Upvotes: 1

Related Questions