views:

506

answers:

3

svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:

<svg ... onload="RunScript(evt);"...>
<script type="text/javascript">
...
function RunScript(loadEvent) {
  // Get object in my html by id
  var objElement = top.document.getElementById('objid1');
  if (objElement)
  {
    // Extend object tag object's methods
    objElement.SVGsetDimension = setDimension;
    ...
  }
  function setDimention(w, h) {...}

In my main html file, the svg is embedded in an object tag like this:

<object id="objid1" data="mygrahic.svg" ... >
<a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10);
   return false;"
...>Set new dimention</a>...

This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:

<object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... >

the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?

Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.

+3  A: 

I think the clue might be in 'on another site'. There are strict rules about when JavaScript programs from different sites are allowed to communicate with teach other. The embedded SVG is being treated the same way a document inside an iframe would.

pdc
+1  A: 

pdc has this one right. Browsers work hard to prevent cross site scripting attacks (XSS) and this is the result. You cannot execute scripts in a document loaded from another domain, or using another port or protocol. For more info you can see: http://en.wikipedia.org/wiki/Same_origin_policy

Prestaul
A: 

So, what you're doing is, from the point of view of a browser, equivalent to the following:

<script>
function stealPassword() {
  var passwordInput = document.querySelector('input[type="password"]');
  var value = passwordInput.value; // My password!
  sendPasswordToServerToStealMyMoney(value);
}
</script>
<iframe src=mybank.com onload=stealPassword()></iframe>

I think you'll understand why this isn't desirable. (There should probably be a warning or an exception in your error console, though.)

Ms2ger