3

I have been following the examples regarding accessing SVG elements using Javascript but I cannot get it to work. What is wrong with this code?

Javascript:

var objTag = document.getElementById('esc-seconds-1s');
objTag.addEventListener('load', function() {
    var svgDoc = objTag.contentDocument;
    var cc3 = svgDoc.getElementById('cc3');
    cc3.setAttribute('fill', 'red');
}, false);

I get the following console error:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

I think the error is a bit miss leading. The error comes from the contentDocument line so I don't think it is because of the same origin policy. Also, I do not have any xlink lines in the SVG file. This is the top of my SVG:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

The SVG displays properly, so why does the objTag.contentDocument call fail?

The html:

<object class="esc-seven-segment" id="esc-seconds-1s"
     type="image/svg+xml" data="images/seven-segment-digit.svg"></object>

Thanks,

-Andres

Andres Gonzalez
  • 2,129
  • 5
  • 29
  • 43
  • See: [Receive Uncaught SecurityError when accessing SVG objects from Javascript](https://stackoverflow.com/questions/24644657/receive-uncaught-securityerror-when-accessing-svg-objects-from-javascript) – Alexander O'Mara May 17 '15 at 04:54

1 Answers1

7

Are you using Chrome and working from local files (ie. file://)?

Using iframe with local files in Chrome

Either run a local webserver (http://localhost/) or try testing with a different browser.

Community
  • 1
  • 1
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181