Ro_Mac
Ro_Mac

Reputation: 13

Why can I not acces with contentDocument to a SVG file in Chrome but I can in Firefox?

I access to my SVG file with Javascript to change the specific Id's fill, it works in Firefox but not in Chrome. This is the error appears in Chrome:

Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a cross-origin frame.

        <script>
          function mapping(elem){
            var map = document.getElementById("Map");
            var mapDoc = map.contentDocument;
            mapDoc.getElementById(elem).style.fill = 'red';
          }
        </script>
        <object id="Map" data="images/Map.svg" type="image/svg+xml"></object>
        <button onclick="mapping('Gus');">Click</button>

Upvotes: 1

Views: 2905

Answers (2)

Robert Longson
Robert Longson

Reputation: 123996

If you're accessing files directly (as you confirm in your comment), Chrome's security model requires that all files be in the same directory.

Firefox has a slightly different security model for file access, it allows sub-resources to be accessed if they are in a sub-directory as well as the current directory.

If you access files via a web server you can use any directory that the web-server allows in any browser.

Upvotes: 3

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

I cannot reproduce the behavior you are observing. My guess is that, the contents of the object tag is blocked by chrome due to same origin policy. So just testing without localhost will not work.

Upvotes: 0

Related Questions