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条)

报告相同问题?

悬赏问题

  • ¥15 我知道什么是混合树,但是怎么写代码啊
  • ¥50 开发板linux系统安装dpkg,apt函数库 有偿
  • ¥15 浏览器时间循环 交互事件和延时事件的 优先级与执行问题
  • ¥15 GD模块安装出错,libgd无法正常安装
  • ¥20 求有缘人帮我把笛卡尔坐标系转换为经纬度 有偿
  • ¥15 vue2中使用计算属性
  • ¥50 远程桌面打开Mastercam、没有许可证、物理机打开正常
  • ¥15 ubuntu安装gdal后java读取tif文件报错
  • ¥15 请问lammps怎么做两种金属连接的原子浓度分布图
  • ¥15 求jacquard数据集