Doing this is astoundingly convoluted. You can see my solution in action here: the methodology is described below (getting the HTML elements, by ID or otherwise, is left as an exercise for the reader).
In the HTML
- Make sure your SVG element includes the attribute
xmlns="http://www.w3.org/2000/svg"
, as you're going to need to take the source of the element as its own file, and the XMLNS declaration is required for standalone SVG files. (Also note that this means your SVG will need to be self-contained and can't refer to elements in its parent document with something like<use>
.) - Optionally, wrap the element in a
<div>
or<span>
, which you may use to get the content of the<svg>
element using.innerHTML
. (Neither theinnerHTML
nor theouterHTML
attributes are present on SVG elements in the current HTML standard.) - Include a
<link rel="icon">
in your page's<head>
.
In JavaScript
- Get the source of the SVG element you want to set as your favicon by getting the
innerHTML
attribute of the HTML element you've wrapped it in, or by callingnew XMLSerializer().serializeToString()
on the SVG element. - Create a DataURL for this element as a document by prepending the string
"data:image/svg+xml,"
to the source. (If most browsers supported SVGs for favicons, we'd be done here, but since, at time of writing, they don't, we must go deeper.) - Create an
<img>
element that you'll be routing the image through, add an event listener to it for theload
event that will draw the image once control returns to the event loop (as spec-compliant browsers won't let you read the image synchronously - see this crbug), and set the DataURL of your SVG source as itssrc
attribute. (The steps between this and step 8 can happen either in sync now, or as part of the listener callback; they just need to happen before you draw the image.) - Decide what resolution you want to render your favicon to - My examples will use 64x64, for compatibility with high-DPI (Retina and Super Retina) displays.
- Create a
<canvas>
element (heretofore referred to ascanvasElement
) and set its dimensions (by settingcanvasElement.width = 64
andcanvasElement.height = 64
). - Create a drawing context for the canvas using
canvasElement.getContext('2d')
(heretofore referred to asctx
). - If you're re-using a canvas you've created beforehand, set
ctx.globalCompositeOperation = "copy"
, or clear it withctx.clearRect(0, 0, 64, 64)
. - Somewhere in the execution sequence following from the
load
listener you added to the<img>
element you created in step 3, draw the image onto the canvas usingctx.drawImage(svgImg, 0, 0, 64, 64)
(wheresvgImg
is the<img>
element you set thesrc
to the SVG DataURL). - Create a PNG DataURL from the canvas using
canvasElement.toDataURL()
, and set that to thehref
attribute of the<link rel="icon">
element in your HTML.