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?

1
  • create object for someSVG.js so like this var some = new SomeSVG() and call some.foo() Commented Aug 24, 2017 at 9:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The SVG must also be same origin or CORS accessible.
@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. HTMLObjectElement.contentWindow isn't included in the apple developer documentation at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.