Accessing SVG from Javascript not working

I'm looking at examples of accessing SVG elements using Javascript, but I can't seem to get it to work. What's 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 am getting 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 mistake is a small mission. The error comes from the contentDocument line, so I don't think it's due to the same origin policy. Also, I have no xlink lines in the SVG file. This is the top of my SVG:

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

      

SVG renders correctly, so why is the call to objTag.contentDocument not working?

html:

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

      

Thank,

-Andres

+3


source to share


1 answer


Are you using Chrome and working with local files (i.e. file://

)?

Using iframe with local files in Chrome



Either start your local web server ( http://localhost/

) or try testing with a different browser.

+7


source







All Articles