2012-04-23 16 views
7

Potrzebuję sposobu, aby uzyskać adres URL favicon z ogólnej strony internetowej, biorąc pod uwagę, że favicon nie zawsze jest pod bazowym adresem URL.Jak uzyskać adres URL favicon z ogólnej strony w JavaScript?

P.s. bez korzystania z zewnętrznej usługi lub biblioteki.

+0

http://en.wikipedia.org/wiki/Favicon#Accessibility zawiera już wiele wskazówek. –

+0

@xRobot: Jeśli chcesz, aby ludzie napisali kod dla ciebie, istnieje kilka stron, które mogą to zrobić. StackOverflow nie jest to miejsce. –

Odpowiedz

8

To wydaje się działać:

var getFavicon = function(){ 
    var favicon = undefined; 
    var nodeList = document.getElementsByTagName("link"); 
    for (var i = 0; i < nodeList.length; i++) 
    { 
     if((nodeList[i].getAttribute("rel") == "icon")||(nodeList[i].getAttribute("rel") == "shortcut icon")) 
     { 
      favicon = nodeList[i].getAttribute("href"); 
     } 
    } 
    return favicon;   
} 

alert(getFavicon());​ 

Albo spojrzeć na http://jsfiddle.net/PBpgY/3/ dla przykładu online.

+0

Dziękuję. Czy istnieje sposób na uzyskanie pełnego adresu URL, a nie tylko /favicon.png? – xRobot

+0

Jeśli spróbujesz tego na stackoverflow.com na przykład, to nie zadziała, ze względu na użyty atrybut "rel =" ikony skrótu "". Spójrz na moje. – sp00m

+0

z tym działa: if ((document.getElementsByTagName ("link") [i] .getAttribute ("rel") == "icon") || (document.getElementsByTagName ("link") [i] .getAttribute ("rel") == "ikona skrótu")). Ale potrzebuję pełnego adresu URL i nie tylko favicon.png :( – xRobot

5

Favicon ma numer /favicon.ico, chyba że masz element <link rel="icon" href="...">. Tak więc można uzyskać wszystkie link elements przez document.getElementsByTagName, a następnie spójrz na każdy z elementów zwróconego NodeList, aby sprawdzić, czy którykolwiek z nich ma atrybut rel o wartości "icon", a jeśli tak, to spójrz na jego href. (Można również spojrzeć na te, gdzie rel jest "shortcut icon" lub "icon shortcut" ze względów historycznych.)

+0

Jak mogę uzyskać element z rel = "ikoną skrótu"? – xRobot

+1

@xRobot: Jak już powiedziałem, przeglądasz 'NodeList', który otrzymałeś z' getElementsByTagName', szukając jednego z 'rel =" ikoną skrótu "' (lub po prostu '" icon "', ponieważ jest to nowsza forma) . 'NodeList' jest indeksowany, więc na przykład, jeśli masz' var list = document.getElementsByTagName ("link"); 'wtedy' list [0] 'jest pierwszym dopasowanym elementem,' list [1] 'jest drugim dopasowanym elementem itp. Istnieje również przydatna własność 'length'. Zobacz dostępne linki. –

14

Dla osób, które wciąż nie otrzymują favikonu z powyższymi kodami;

  1. Większość przeglądarek obsługuje coraz favicon wysyłając żądanie (/favicon.ico) siebie, zamiast w html.

  2. Innym rozwiązaniem jest Google.

    Aby uzyskać favicon dla domeny, należy:
    https://plus.google.com/_/favicon?domain=www.stackoverflow.com

    Aby uzyskać favicon dla adresu URL, przeznaczenie:
    https://plus.google.com/_/favicon?domain_url=http://www.stackoverflow.com

2

żywo pracuje skrzypce przykład: http://jsfiddle.net/sc8qp/2/

Tylko dla dobrej miary i kompletności bez regex:

function getIcons() { 
    var links = document.getElementsByTagName('link'); 
    var icons = []; 

    for(var i = 0; i < links.length; i++) { 
     var link = links[i]; 

     //Technically it could be null/undefined if someone didn't set it! 
     //People do weird things when building pages! 
     var rel = link.getAttribute('rel'); 
     if(rel) { 
      //I don't know why people don't use indexOf more often 
      //It is faster than regex for simple stuff like this 
      //Lowercase comparison for safety 
      if(rel.toLowerCase().indexOf('icon') > -1) { 
       var href = link.getAttribute('href'); 

       //Make sure href is not null/undefined    
       if(href) { 
        //Relative 
        //Lowercase comparison in case some idiot decides to put the 
        //https or http in caps 
        //Also check for absolute url with no protocol 
        if(href.toLowerCase().indexOf('https:') == -1 && href.toLowerCase().indexOf('http:') == -1 
         && href.indexOf('//') != 0) { 

         //This is of course assuming the script is executing in the browser 
         //Node.js is a different story! As I would be using cheerio.js for parsing the html instead of document. 
         //Also you would use the response.headers object for Node.js below. 

         var absoluteHref = window.location.protocol + '//' + window.location.host; 

         if(window.location.port) { 
          absoluteHref += ':' + window.location.port; 
         } 

         //We already have a forward slash 
         //On the front of the href 
         if(href.indexOf('/') == 0) { 
          absoluteHref += href; 
         } 
         //We don't have a forward slash 
         //It is really relative! 
         else { 
          var path = window.location.pathname.split('/'); 
          path.pop(); 
          var finalPath = path.join('/'); 

          absoluteHref += finalPath + '/' + href; 
         } 

         icons.push(absoluteHref); 
        } 
        //Absolute url with no protocol 
        else if(href.indexOf('//') == 0) { 
         var absoluteUrl = window.location.protocol + href; 

         icons.push(absoluteUrl); 
        } 
        //Absolute 
        else { 
         icons.push(href); 
        } 
       } 
      } 
     } 
    } 

    return icons; 
} 
Powiązane problemy