I am working on a bookmarklet (currently just javascript code) that will prompt the user, asking for a domain name, and whatever domain name they enter will change the favicon of the current site they are on to the one of the domain they entered. I have gotten the code to work without errors, but the favicon doesn't change.
The code does not error, it simply prints "Favicon changed" in the console, but nothing changes.
here is my code:
var script = document.createElement('script');
script.src = '//code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var waitForJQuery = setInterval(function () {
if (typeof $ != 'undefined') {
function changeFavicon(src) {
$('link[rel="shortcut icon"]').attr('href', src);
}
let url;
url = prompt("Please enter the URL you wish to mask this page as. Example: www.google.com", "www.google.com");
changeFavicon("//www.google.com/s2/favicons?domain=" url);
console.log("Favicon Changed!");
clearInterval(waitForJQuery);
}
}, 10);
Edit: I would like to let it be known I am very inexperienced with javascript, I originally came from Python so I know a bit but a lot of this code may be inefficient or defective. if that is the case feel free to comment or message me about it! Thanks :D
Edit 2: I have tried some other code, this time eliminating jquery.
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
let url;
url = prompt("Please enter the URL you wish to mask this page as. Example: google.com", "google.com");
iconURL = "//www.google.com/s2/favicons?domain=" url
changeFavicon(iconURL);
It still does not work though.
CodePudding user response:
I have found the thing that was wrong!
www.google.com/s2/favicons?domain=
does NOT Return an ico file so it failed to work because of so.
CodePudding user response:
Consider the following.
$(function() {
function getIcon(url) {
var myData = [
"//www.google.com/s2/favicons?domain=" url
]
if (url) {
$.get(myData[0], function(results) {
console.log(results);
myData.push(results);
});
}
return myData;
}
$("#get-btn").click(function() {
var newIcon = getIcon($("#url").val());
$("<div>").appendTo($(".prompt"));
$("<img>", {
class: "shortcut icon",
src: newIcon[0]
}).appendTo($(".prompt > div"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="prompt">
<p>Please enter the URL you wish to mask this page as.</p>
<input type="text" id="url" placeholder="www.google.com">
<button id="get-btn">Get FavIcon</button>
</div>