0

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?

Community
  • 1
  • 1
quackkkk
  • 139
  • 1
  • 13
  • 3
    That is invalid html. You cannot wrap the `head` nor the `body` in a `div`. – Gabriele Petrioli Mar 13 '17 at 19:03
  • The ultimate goal is to change the favicon while mantaining some custom CSS on the whole page - that's why I have a div wrapping head and body. If this is not possible with the current html structure (because as Gaby points out is invalid), I'll have to rethink the design. – quackkkk Mar 13 '17 at 19:15
  • I need the `div` so I can apply `background-image`, it won't work if I refer directly to `html`. @wOxxOm – quackkkk Mar 13 '17 at 19:41
  • 2
    Why do you think it won't work with `html`? It works here. You may need to increase specificity via `!important` though. – wOxxOm Mar 13 '17 at 19:43
  • I tried to apply `background-image` directly to `html` but it wasn't working because of **"web_accessible_resources"**. Now I got it to work. Many thanks for your questioning @wOxxOm, overall architechture of the extension has improved! – quackkkk Mar 13 '17 at 20:05

1 Answers1

0

<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.

Keith
  • 150,284
  • 78
  • 298
  • 434
  • Just to confirm, is there any html element that would be valid between `` and ``? Perhaps ``? – quackkkk Mar 14 '17 at 14:46
  • @quackkkk afraid not: [**Permitted content** One `` element, followed by one `` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) – Keith Mar 14 '17 at 16:09