停止使用 SVG 元素中的数据网址

小康纯 (Jun Kokatsu)
小康纯

我们最近更新了 SVG 规范,不再支持在 SVG <use> 元素中使用 data: 网址。 由于 Webkit 不支持 SVG <use> 元素中的 data: 网址,因此这有助于提高 Web 平台的安全性以及浏览器之间的兼容性。

移除原因

SVG <use> 元素可以提取外部 SVG 图片,并将其克隆到当前文档中。这是一项强大的功能,因此仅限于同源 SVG 图片。不过,data: 网址被视为同源资源,这会导致一些安全 bug,例如绕过 Trusted TypesSanitizer API。 在讨论这些安全错误时,我们讨论了最佳解决方法。我们已在浏览器供应商(来自 MozillaApple)之间达成共识,即不再支持 SVG <use> 元素中的 data: 网址。

对于在 SVG <use> 元素中使用 data: 网址的网站,有几种替代方案。

使用同源 SVG 图片

您可以使用 <use> 元素加载同源 SVG 图片。

<div class="icon">
  <svg width="1em" height="1em">
    <use xlink:href="svgicons.svg#user-icon"></use>
  </svg>
</div>

使用内嵌 SVG 图片

您可以使用 <use> 元素引用内嵌 SVG 图片。

<svg style="display:none" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol id="user-icon" viewBox="0 0 32 32">
      <path d="M25.333 9.335c0 5.153-4.179 9.333-9.333 9.333s-9.333-4.18-9.333-9.333c0-5.156 4.179-9.335 9.333-9.335s9.333 4.179 9.333 9.335zM23.203 18.908c-2.008 1.516-4.499 2.427-7.203 2.427-2.707 0-5.199-0.913-7.209-2.429-5.429 2.391-8.791 9.835-8.791 13.095h32c0-3.231-3.467-10.675-8.797-13.092z">
    </symbol>
    <!-- And potentially many more icons -->
  </defs>
</svg>

<div class="icon">
  <svg width="1em" height="1em">
    <use xlink:href="#user-icon"></use>
  </svg>
</div>

将 SVG 图片与 blob 搭配使用:网址

如果您无法控制网页的 HTML 或同源资源(例如 JavaScript 库),可以在 <use> 元素中使用 blob: 网址加载 SVG 图片。

const svg_content = `<svg style="display:none" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
      <symbol id="user-icon" viewBox="0 0 32 32">
        <path d="M25.333 9.335c0 5.153-4.179 9.333-9.333 9.333s-9.333-4.18-9.333-9.333c0-5.156 4.179-9.335 9.333-9.335s9.333 4.179 9.333 9.335zM23.203 18.908c-2.008 1.516-4.499 2.427-7.203 2.427-2.707 0-5.199-0.913-7.209-2.429-5.429 2.391-8.791 9.835-8.791 13.095h32c0-3.231-3.467-10.675-8.797-13.092z">
      </symbol>
      <!-- And potentially many more icons -->
    </defs>
  </svg>`;
const blob = new Blob([svg_content], {type: 'image/svg+xml'});
const url = URL.createObjectURL(blob);
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttribute('href', url + '#user-icon');
svg.appendChild(use);
document.body.appendChild(svg);

实时示例

您可以在 GitHub 上找到这些替代方案的实际示例