Search code examples
javascripthtmldomgoogle-chrome-extensionfavicon

Changing website favicon dynamically: how to when div wraps head


I've found this solution to change a favicon using the code in content.js (run_at: document_end) of my Chrome extension:

(function() {
    var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.stackoverflow.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
}());

The above works wonders.

The problem arises when wrapping the whole document in a div to later apply some necessary custom CSS.

<html>
  <div id="allContent">
    <head></head>
    <body></body>
  </div>
</html>

In this situation the first code above doesn't change the favicon. I've tried changing its last line to:

document.getElementById("allContent").getElementsByTagName('head')[0].appendChild(link);

Although the link gets inserted correctly (at the bottom of <head> inside <div id="allContent">) the favicon doesn't change.

Anyone knows why?


Solution

  • <div> is not valid between <html> and <head>. The rendering engine will work around it, but expect odd side effects like the meta properties (like <link rel="icon" ... >) being unpredictable or ignored.