Jump to content

Adding Favicon Using JS


shifferman
 Share

Recommended Posts

Hello,I am looking for a way to add a favicon to a website using JS. I am familiar with the regular way to do it - via the <head> section - but the problem is right there, I have no access to the <head> section, only to the <body> (I have no access to the server, it's an affiliated site). So I am looking for a way to do it from the <body> section. If someone knows of a way, please let me know.Thank you. :)

Link to comment
Share on other sites

I got curious, so I tried this code:

var myHead = document.getElementsByTagName('head')[0];var myLink = document.createElement('link');myLink.href = "favicon.ico";myLink.rel = "shortcut icon";myHead.insertBefore(myLink, myHead.firstChild);

In every browser I tried, the element was successfully added to the DOM. But being in the DOM is not enough.Firefox actually did what you want, and the icon was displayed. Chrome/Safari did not display it, and neither did Explorer 7-8.This was the behavior I actually expected. My guess is that most browsers only look for the favicon at page load, and then they're done with that. This is really sort of dumb, since essentially the same technique will cause any browser to change the src of a stylesheet link.Then again, it may have something to do with the way browsers look for a favicon one place, then another, then another, till success or failure. That makes the icon link quite a bit different from a stylesheet link.Either way, disappointing.

Edited by Deirdre's Dad
Link to comment
Share on other sites

I've done some Googling in addition to the tests I ran earlier. It looks like Firefox and Opera really are the only browsers that support this. Everyone who's tested it says the same thing, and no one says different. Game over.

Link to comment
Share on other sites

  • 2 months later...
Guest trlkly
I've done some Googling in addition to the tests I ran earlier. It looks like Firefox and Opera really are the only browsers that support this. Everyone who's tested it says the same thing, and no one says different. Game over.
You can do it in Chrome, too. You just have to use the iframe shim. It's how people on userscript.org get their favicon changing scripts to work on Chrome.That said, it's still game over if you want to maintain IE support, even if IE9 supports it.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...