Last active
February 21, 2024 05:26
-
-
Save elliz/bb7661d8ed1535c93d03afcd0609360f to your computer and use it in GitHub Desktop.
Tampermonkey script to update Favicon with data-uri SVG for Chrome 80+ etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name SVG Favicon test | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Update the favicon on a site | |
// @author You | |
// @match https://elliz.github.io/svg-favicon/ | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
// play with https://codepen.io/elliz/full/ygvgay for getting it right | |
// viewBox is required but does not need to be 16x16 | |
const svg = ` | |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"> | |
<circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" /> | |
<circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" /> | |
</svg> | |
`; | |
var favicon_link_html = document.createElement('link'); | |
favicon_link_html.rel = 'icon'; | |
favicon_link_html.href = svgToDataUri(svg); | |
favicon_link_html.type = 'image/svg+xml'; | |
try { | |
let favicons = document.querySelectorAll('link[rel~="icon"]'); | |
favicons.forEach(function(favicon) { | |
favicon.parentNode.removeChild(favicon); | |
}); | |
const head = document.getElementsByTagName('head')[0]; | |
head.insertBefore( favicon_link_html, head.firstChild ); | |
} | |
catch(e) { } | |
// functions ------------------------------- | |
function escapeRegExp(str) { | |
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); | |
} | |
function replaceAll(str, find, replace) { | |
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); | |
} | |
function svgToDataUri(svg) { | |
var encoded = svg.replace(/\s+/g, " ") | |
encoded = replaceAll(encoded, "%", "%25"); | |
encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements | |
encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css | |
encoded = replaceAll(encoded, "<", "%3c"); | |
encoded = replaceAll(encoded, ">", "%3e"); | |
encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text> | |
encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox | |
encoded = replaceAll(encoded, "{", "%7b"); | |
encoded = replaceAll(encoded, "}", "%7d"); | |
encoded = replaceAll(encoded, "|", "%7c"); | |
encoded = replaceAll(encoded, "^", "%5e"); | |
encoded = replaceAll(encoded, "`", "%60"); | |
encoded = replaceAll(encoded, "@", "%40"); | |
var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim(); | |
return dataUri; | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment