简体   繁体   English

如何在 html 中嵌入 SVG<object> 来自 Cross Origin url 的标签说 (s3_url/image.svg)

[英]How to embed SVG in html <object> tag from Cross Origin url say (s3_url/image.svg)

I went through all the possible resources I could find on the internet, MDN, W3C etc. but nowhere could I find any documentation regarding cors.我浏览了我可以在互联网、MDN、W3C 等上找到的所有可能的资源,但我找不到任何关于 cors 的文档。

I'm trying to embed an SVG in HTML .我正在尝试在 HTML 中嵌入一个 SVG 。 It works fine in same origin URL它在同源 URL 中工作正常

<object id="obj1" data="same_origin_url/image.svg"></object>

On using cross_origin_url, it is not able to embed the SVG.使用 cross_origin_url 时,无法嵌入 SVG。

<object id="obj2" data="cross_origin_url/image.svg"></object>

in the 1st case, I can access the SVG using the following code and do the required manipulation (like changing color) on the SVG.在第一种情况下,我可以使用以下代码访问 SVG 并在 SVG 上执行所需的操作(如更改颜色)。

document.getElementById('obj1').contentDocument.getElementByTagName('svg')

while in the 2nd case, it returns throws an error as contentDocument of obj2 returns null.而在第二种情况下,它返回抛出错误,因为 obj2 的 contentDocument 返回 null。

document.getElementById('obj2').contentDocument.getElementByTagName('svg')

On webserver that hosts Your svg file You must set response Access-Control-Allow-Origin header.在托管您的 svg 文件的网络服务器上,您必须设置响应 Access-Control-Allow-Origin 标头。 For example for Apache webserver You must enable mod_headers and configure it in Your configuration for Your server in config files or .htaccess.例如对于 Apache 网络服务器,您必须启用 mod_headers 并在配置文件或 .htaccess 中为您的服务器配置它。

    <IfModule mod_headers.c>
        <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css|js|gif|png|jpe?g|svg|svgz|ico|webp)$">
            Header set Access-Control-Allow-Origin "*"
        </FilesMatch>
    </IfModule>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM