Skip to content

Commit d48b71b

Browse files
committed
fix(): use DOMParser with "image/svg+xml" to parse svg
1 parent a7fd3cf commit d48b71b

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

bricks/icons/src/shared/SvgCache.ts

+8-11
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,15 @@ export function constructSvgElement(
2929
retryable: boolean,
3030
options?: ResolveIconOptions
3131
): SVGResult | null {
32-
const div = document.createElement("div");
33-
div.innerHTML = content;
34-
35-
const svg = div.firstElementChild;
36-
if (svg?.tagName?.toLowerCase() !== "svg")
37-
return retryable ? CACHEABLE_ERROR : null;
38-
3932
if (!parser) parser = new DOMParser();
40-
const doc = parser.parseFromString(svg.outerHTML, "text/html");
41-
42-
const svgEl = doc.body.querySelector("svg");
43-
if (!svgEl) return retryable ? CACHEABLE_ERROR : null;
33+
// Requires `xmlns`for the SVG to be parsed correctly
34+
const refinedContent = content.includes("xmlns=")
35+
? content
36+
: content.replace(/(<svg)(\s)/i, '$1 xmlns="http://www.w3.org/2000/svg"$2');
37+
const doc = parser.parseFromString(refinedContent, "image/svg+xml");
38+
const svgEl = doc.documentElement;
39+
if (!(svgEl instanceof SVGSVGElement))
40+
return retryable ? CACHEABLE_ERROR : null;
4441

4542
const titles = svgEl.querySelectorAll("title");
4643
for (const title of titles) {

0 commit comments

Comments
 (0)