Changing website favicon dynamically

前端 未结 15 1322
温柔的废话
温柔的废话 2020-11-22 02:17

I have a web application that\'s branded according to the user that\'s currently logged in. I\'d like to change the favicon of the page to be the logo of the private label,

15条回答
  •  遇见更好的自我
    2020-11-22 02:43

    A more modern approach:

    const changeFavicon = link => {
      let $favicon = document.querySelector('link[rel="icon"]')
      // If a  element already exists,
      // change its href to the given link.
      if ($favicon !== null) {
        $favicon.href = link
      // Otherwise, create a new element and append it to .
      } else {
        $favicon = document.createElement("link")
        $favicon.rel = "icon"
        $favicon.href = link
        document.head.appendChild($favicon)
      }
    }
    

    You can then use it like this:

    changeFavicon("http://www.stackoverflow.com/favicon.ico")
    

提交回复
热议问题