1

This is a similar question but I would like to know how to access the SVG's JavaScript functions when they are not embedded but are imported from an external file:

Call svg javascript function inside html javascript function

So, I'll attempt to make my question clear and hopefully not too convoluted.

I have main.html and main.js.

I also have someSVG.svg which imports someSVG.js which has a function, foo().

main.html imports someSVG.svg as an object element.

How do I call foo() from main.js?

David Smith
  • 892
  • 1
  • 6
  • 16

1 Answers1

2

Provided you embed the SVG with an <object> tag, you can access the window object of the SVG with

var inner = document.querySelector('object').contentWindow

Just like the window object of the outer window, it provides all global variables that you would find in normal window, for example a script-defined inner.foo() or inner.document.

NOTE: Safari supports HTMLObjectElement.contentDocument from version 10, but not .documentWindow.

ccprog
  • 20,308
  • 4
  • 27
  • 44
  • The SVG must also be same origin or CORS accessible. – Robert Longson Oct 24 '17 at 23:31
  • @TheBlueCrayon wanted to comment, but couldn't because of missing reputation. He left an edit instead. Here's the full text: Safari doesn't support HTMLObjectElement.contentWindow for svg elements. Tested in Safari 11 and older for both Mac and iOS with this [simplified test case](https://plnkr.co/edit/lrf1qCcxY0NtU70GSI09?p=preview). HTMLObjectElement.contentWindow isn't included in the [apple developer documentation](https://developer.apple.com/documentation/webkitjs/htmlobjectelement?changes=latest_majo) at all. – ccprog Oct 27 '17 at 21:31