Cross-domain SVG content document in object tag

2019-03-04 14:15发布

问题:

Is it 'legal' to have an SVG with a data in a foreign domain i.e. (data="//da86ge957603k.cloudfront.net/rails/grafitti_logo-f4e8238a87c979c0cf5b41481c982b71.svg"), and then bind a load event to the object and then access the object's SVG DOM through the contentdocument property? I can do this when the SVG is on the local domain, but whenever I try to host the SVG elsewhere, I get "this.contentDocument is null" errors. I have tried getSVGDocument() as well. I can't find anywhere that says this is a cross-domain security problem, and from what I can tell this should be permissible with an object tag being used for the SVG (I am not using an iFrame). I appreciate you taking the time to help me. Here is the code I am using to embed the object and bind, and try to access the DOM (as I said this works when the SVG is on the local domain).

 <object id="gangstergraffiti" type="image/svg+xml" data="<%= image_url("grafitti_logo.svg") %>">Gangster</object>

$("#gangstergraffiti").each(function() {
  this.addEventListener('load', svgGangsterGraffitiReady, false);
});

function svgGangsterGraffitiReady(){
  var graffitistrokes = this.contentDocument.getElementsByClassName('graffiti');
  for (var i = 0; i < graffitistrokes.length; i++) {
    graffitistrokes[i].setAttribute("stroke", "white");
    graffitistrokes[i].setAttribute("fill", "white");
  }
}

Dan

回答1:

It's documented here by w3c. In detail here for the object tag that you can't do cross domain access to the data of a <object> tag except via CORS.

There's a more readable distillation on MDN and to get round it you need to enable CORS on the remote site (if you can).