bubkoo / html-to-image

✂️ Generates an image from a DOM node using HTML5 canvas and SVG.
MIT License
5.39k stars 503 forks source link

Crash on svg with <use> tags referencing external svg files #425

Open strindhaug opened 10 months ago

strindhaug commented 10 months ago

If the html contains svg with an external svg-file in the use tag then the html-to-image functions crash.

Expected Behavior

I'd expect it to work without issue.

Current Behavior

The javascript crashes, with a message saying something like

Document.querySelector: '/gfx/sprites.svg?v=v123#some-icon' is not a valid selector

Possible Solution

It looks like the code in ensureSVGSymbols blindly assumes the xlink:href attribute is a valid queryselector to an svg element elsewhere in the document. I'm pretty sure the xlink:href and href attribute is not required to be a valid queryselector since the spec says it's an URL: https://www.w3.org/TR/SVG2/struct.html#UseElementHrefAttribute and it does work on our website.

The fact that it works when the use-tag refers to an embedded element is mostly an accident.

I'm not quite sure how to fix it so that ensureSVGSymbols would work with both files and local references; but at least if you wrapped these two querySelector's in try/catch or verify that the "id" variable is a valid css selector before using it, it would at least not crash, and you'll still get an image possibly missing a few icons rather than nothing.

Steps To Reproduce

Try to use any of toPng, toJpeg, toBlob, toPixelData, toSvg on html containing an svg defined something like this:

<svg viewBox="0 0 135 57"><use xlink:href="/gfx/sprites.svg?v=v123#some-icon" href="/gfx/sprites.svg?v=v123#some-icon"></use></svg>
vivcat[bot] commented 10 months ago

👋 @strindhaug

Thanks for opening your first issue here! If you're reporting a 🐞 bug, please make sure you include steps to reproduce it. To help make it easier for us to investigate your issue, please follow the contributing guidelines.

We get a lot of issues on this repo, so please be patient and we will get back to you as soon as we can.

Tilesto commented 8 months ago

Absolutely the same issue. Not working with sprites +1

MatthiasGrandl commented 8 months ago

+1

cgmonte commented 8 months ago

+1