dongluyi5123 2014-01-10 17:11
浏览 111
已采纳

通过Javascript下载网站的favicon.ico

I've tried Ajax:

$.ajax({
  type : "GET",
  url : "http://getfavicon.appspot.com/http://www.google.com",
  success : function(result) {
      // use the .ico result somewhere
  }
});

which gives me the error:

XMLHttpRequest cannot load http://getfavicon.appspot.com/http://www.google.com. No
'Access-Control-Allow-Origin' header is present on the requested resource. Origin
'http://localhost' is therefore not allowed access.

So I tried to allow CORS on my Apache server, but found out the site I download from needs to have CORS allowed too. And if I understand this right I can't download anything from an external domain through javascript, images, text, whatnot?

I tried to go around this by calling a php script on my webserver through ajax instead:

var domain = "www.google.com";
$.ajax({
   type : "POST",
   url : "php/fetchIcon.php",
   data : {
     'domainName' : domain
   },
   success : function(result) {
     // use the .ico result somewhere
   }
});

fetchIcon.php:

$domainName = false;
if(isset($_POST['domainName'])){
    $domainName = $_POST['domainName'];
}
echo file_get_contents("http://getfavicon.appspot.com/http://".$domainName, true);

In the Ajax success result I get back the image's binary code, but it seems broken in some way.

  1. If I want to display the .ico file, can I do something like: "document.getElementById("img").src = result;" ? In my project I want to use "THREE.ImageUtils.loadTexture(result);". But that's a bit too much for this question.

  2. Do I need to use Base64 encoding/decoding and how?

  3. Is there an easier way or hack to do it just in Javascript without PHP?

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • douao3063 2014-01-10 17:42
    关注

    This worked for me, answered by Rocket Hazmat:

    fetchIcon.php:

    $domainName = false;
    if(isset($_GET['domainName'])){
        $domainName = $_GET['domainName'];
    }
    echo file_get_contents("http://getfavicon.appspot.com/http://".$domainName, true);
    

    Simplest way to display that it worked without CORS restrictions:

          <img src="fetchIcon.php?domainName=www.google.com" />
    

    Otherwise this would have been sufficient:

          <img src="http://getfavicon.appspot.com/http://www.google.com"/> 
    

    or the way I wanted to load a new texture uniform in THREE.js, in javascript, which I kept outside the question, but maybe someone run into the same problem as me:

    iconUniform.map.value = THREE.ImageUtils.loadTexture("fetchIcon.php?domainName=www.google.com");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料