Skip to content

Instantly share code, notes, and snippets.

@LenAnderson
Last active January 9, 2024 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenAnderson/bc859ad19cb454f314fad58797afcaef to your computer and use it in GitHub Desktop.
Save LenAnderson/bc859ad19cb454f314fad58797afcaef to your computer and use it in GitHub Desktop.
Bring Your Own Favicon
// ==UserScript==
// @name Bring Your Own Favicon
// @namespace https://github.com/LenAnderson
// @version 1.0.0
// @description Use your own favicon
// @author LenAnderson
// @match *://*/*
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
(function() {
'use strict';
const get = ()=>{
return JSON.parse(GM_getValue('byof', '[]'));
};
const set = (value)=>{
GM_setValue('byof', JSON.stringify(value));
};
const updateFavicon = ()=>{
const urls = get().filter(it=>location.href.startsWith(it.start)).toSorted((a,b)=>b.start.length-a.start.length);
if (urls.length == 0) return;
const url = urls[0];
let link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link'); {
link.rel = 'icon';
document.head.append(link);
}
}
link.href = url.favicon;
};
updateFavicon();
GM_registerMenuCommand('Set Favicon', ()=>{
const urls = get();
const start = prompt(`You have custom favicons set URLs starting with:\n\n${urls.map(it=>it.start).join('\n')}\n\nAdd a new favicon for URLs starting with:`, location.href);
if (start) {
const favicon = prompt(`You are setting a custom favicon for all URLs starting with:\n${start}\n\nEnter a data URI:`);
if (favicon) {
const old = urls.find(it=>it.start.toLowerCase() == start.toLowerCase());
if (old) {
old.favicon = favicon;
} else {
urls.push({start, favicon});
}
set(urls);
updateFavicon();
}
}
});
GM_registerMenuCommand('Remove Favicon', ()=>{
const urls = get();
const idx = prompt(`You have custom favicons set URLs starting with:\n\n${urls.map((it,idx)=>`${idx}: ${it.start}`).join('\n')}\n\nEnter the number of the favicon you want to remove:`);
if (idx !== null) {
urls.splice(idx, 1);
set(urls);
updateFavicon();
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment