Cambiar el favicon del sitio web dinámicamente


Tengo una aplicación web que está marcada de acuerdo con el usuario que está conectado actualmente. Me gustaría cambiar el favicon de la página para que sea el logotipo de la etiqueta privada, pero no puedo encontrar ningún código ni ningún ejemplo de cómo hacer esto. Alguien ha hecho esto con éxito antes?

Me estoy imaginando tener una docena de iconos en una carpeta, y la referencia a que favicon.el archivo ico a usar se genera dinámicamente junto con la página HTML. ¿Pensamientos?

Author: Michał Perłakowski, 2008-11-04

13 answers

¿Por qué no?

(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);
})();

Firefox debería estar bien con él.

editado para sobrescribir correctamente los iconos existentes

 294
Author: keparo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-21 12:23:22

Aquí hay un código que funciona en Firefox, Opera y Chrome (a diferencia de cualquier otra respuesta publicada aquí). Aquí hay otra demo de código que también funciona en IE11. Es posible que el siguiente ejemplo no funcione en Safari o Internet Explorer.

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

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);
}

Entonces lo usarías de la siguiente manera:

var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
 changeFavicon('http://www.google.com/favicon.ico');
};

Fork away o ver una demostración.

 72
Author: Mathias Bynens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 06:29:14

Si tiene el siguiente fragmento HTML:

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

Puedes cambiar el favicon usando Javascript cambiando el elemento HREF en este enlace, por ejemplo (asumiendo que estás usando jQuery):

$("#favicon").attr("href","favicon2.png");

También puede crear un elemento Canvas y establecer el HREF como un toDataURL() del canvas, al igual que el Favicon Defender lo hace.

 39
Author: fserb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-10 09:04:58

JQuery Version:

$("link[rel='shortcut icon']").attr("href", "favicon.ico");

O incluso mejor:

$("link[rel*='icon']").attr("href", "favicon.ico");

Versión JS de vainilla:

document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";

document.querySelector("link[rel*='icon']").href = "favicon.ico";
 30
Author: vorillaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 23:37:14

Aquí hay un código que uso para agregar soporte de favicon dinámico a Opera, Firefox y Chrome. Sin embargo, no pude conseguir que IE o Safari funcionaran. Básicamente Chrome permite favicons dinámicos, pero solo los actualiza cuando la ubicación de la página (o un iframe etc en ella) cambia por lo que puedo decir:

var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
    change: function(iconURL) {
        if (arguments.length == 2) {
            document.title = optionalDocTitle}
        this.addLink(iconURL, "icon")
        this.addLink(iconURL, "shortcut icon")

        // Google Chrome HACK - whenever an IFrame changes location 
        // (even to about:blank), it updates the favicon for some reason
        // It doesn't work on Safari at all though :-(
        if (!IE) { // Disable the IE "click" sound
            if (!window.__IFrame) {
                __IFrame = document.createElement('iframe')
                var s = __IFrame.style
                s.height = s.width = s.left = s.top = s.border = 0
                s.position = 'absolute'
                s.visibility = 'hidden'
                document.body.appendChild(__IFrame)}
            __IFrame.src = 'about:blank'}},

    addLink: function(iconURL, relValue) {
        var link = document.createElement("link")
        link.type = "image/x-icon"
        link.rel = relValue
        link.href = iconURL
        this.removeLinkIfExists(relValue)
        this.docHead.appendChild(link)},

    removeLinkIfExists: function(relValue) {
        var links = this.docHead.getElementsByTagName("link");
        for (var i=0; i<links.length; i++) {
            var link = links[i]
            if (link.type == "image/x-icon" && link.rel == relValue) {
                this.docHead.removeChild(link)
                return}}}, // Assuming only one match at most.

    docHead: document.getElementsByTagName("head")[0]}

Para cambiar favicons, simplemente vaya favicon.change("ICON URL") usando lo anterior.

(créditos para http://softwareas.com/dynamic-favicons para el código en el que basé esto.)

 9
Author: cryo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-27 09:10:42

El favicon se declara en la etiqueta head con algo como:

<link rel="shortcut icon" type="image/ico" href="favicon.ico">

Debería ser capaz de simplemente pasar el nombre del icono que desea a lo largo de los datos de vista y lanzarlo en la etiqueta head.

 9
Author: Jeff Sheldon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-11 08:00:50

Un enfoque más moderno:

const changeFavicon = link => {
  let $favicon = document.querySelector('link[rel="icon"]')
  // If a <link rel="icon"> 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 <head>.
  } else {
    $favicon = document.createElement("link")
    $favicon.rel = "icon"
    $favicon.href = link
    document.head.appendChild($favicon)
  }
}

Puedes usarlo así:

changeFavicon("http://www.stackoverflow.com/favicon.ico")
 9
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 21:30:32

Usaría el enfoque de Greg y haría un manejador personalizado para favicon.ico Aquí hay un manejador (simplificado) que funciona:

using System;
using System.IO;
using System.Web;

namespace FaviconOverrider
{
    public class IcoHandler : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/x-icon";
        byte[] imageData = imageToByteArray(context.Server.MapPath("/ear.ico"));
        context.Response.BinaryWrite(imageData);
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public byte[] imageToByteArray(string imagePath)
    {
        byte[] imageByteArray;
        using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
        {
        imageByteArray = new byte[fs.Length];
        fs.Read(imageByteArray, 0, imageByteArray.Length);
        }

        return imageByteArray;
    }
    }
}

Entonces puede usar ese manejador en la sección HttpHandlers de la configuración web en IIS6 o usar la característica 'Asignaciones de manejador' en IIS7.

 5
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-25 04:52:17

La única manera de hacer que esto funcione para IE es configurar su servidor web para tratar las solicitudes de *.ico para llamar a su lenguaje de scripting del lado del servidor (PHP,. NET, etc.). También configurar*.redirect para redirigir a un solo script y hacer que este script entregue el archivo favicon correcto. Estoy seguro de que todavía va a haber algunos problemas interesantes con la caché si quieres ser capaz de rebotar hacia adelante y hacia atrás en el mismo navegador entre diferentes favicons.

 3
Author: Greg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-24 16:19:50

De acuerdo con WikiPedia, puede especificar qué archivo favicon cargar utilizando la etiqueta link en la sección head, con un parámetro de rel="icon".

Por ejemplo:

 <link rel="icon" type="image/png" href="/path/image.png">

Imagino que si quisiera escribir algún contenido dinámico para esa llamada, tendría acceso a las cookies para poder recuperar la información de su sesión de esa manera y presentar el contenido apropiado.

Puede caer en falta de formatos de archivo (IE, según se informa, solo soporta es .formato ICO, mientras que la mayoría todos los demás admiten imágenes PNG y GIF) y posiblemente problemas de almacenamiento en caché, tanto en el navegador como a través de proxies. Esto sería debido a la itention original de favicon, específicamente, para marcar un marcador con el mini-logo de un sitio.

 2
Author: staticsan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-04 04:23:13

Sí totalmente posible

  • Use un querystring después del favicon.ico (y otros archivos enlaces - ver el enlace de respuesta a continuación)
  • Simplemente asegúrese de que el servidor responde al "someUserId" con el archivo de imagen correcto (que podría ser reglas de enrutamiento estáticas, o dynamic server side code).

Por ejemplo

<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">

Entonces sea cual sea el lenguaje / marco del lado del servidor que use, podrá encontrar fácilmente el archivo basado en el userId y lo servirá en respuesta a esa solicitud.

Pero hacer favicons correctamente (en realidad es un realmente asunto complejo) por favor vea la respuesta aquí https://stackoverflow.com/a/45301651/661584

Mucho mucho más fácil que resolver todos los detalles usted mismo.

Disfruta.

 2
Author: MemeDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-25 11:33:22

Hay una solución de una sola línea para aquellos que usan jQuery:

$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
 0
Author: user9542596,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-02 15:24:50

Utilizo favico.js en mis proyectos:)

 -1
Author: Oscar Nevarez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-13 04:32:57