【问题标题】:How to get all the favicon from the site, by url如何通过 url 从网站获取所有网站图标
【发布时间】:2021-11-17 07:10:25
【问题描述】:

这是我的解析器:

let getFavicon = function () {
  let favicons = [];
  let nodeList = document.getElementsByTagName('link');
  for (let i = 0; i < nodeList.length; i++) {
    if (
      nodeList[i].getAttribute('rel') === 'icon' ||
      nodeList[i].getAttribute('rel') === 'shortcut icon'
    ) {
      favicons.push(nodeList[i].getAttribute('href'));
    }
  }
  return favicons;
};

它返回一个 URL 数组,包含所有 URL 图标。

用户如何获得这些网站图标?在输入中输入 URL 并获取网站图标时。

像谷歌标签一样,我们输入 URL 并获取带有 favicon 的标签

我怎样才能做同样的事情?

【问题讨论】:

  • 如果您要问如何创建一个页面,用户可以在其中输入 URL 并且您的网站进行解析,您会想要执行 ajax get 请求然后解析您网站上的 html。

标签: javascript parsing dom


【解决方案1】:

我希望这个例子会有所帮助:

    let favicons = [];
let nodeList = document.getElementsByTagName("link");
for (let i = 0; i < nodeList.length; i++) {
    if ((nodeList[i].getAttribute("rel") === "icon") || (nodeList[i].getAttribute("rel") === "shortcut icon")) {
        favicons.push(nodeList[i].getAttribute("href"))
    }
}

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return strArray[j];
    }
    return -1;
}

const searchTextBox = document.querySelector('input[name="search"]')

searchTextBox.addEventListener('keyup', (e) => {
    
    const searchResult = searchStringInArray(e.target.value, favicons)
    
    if(searchResult != -1){
        document.querySelector('.icon').style.background = `url('${searchResult}')` 
    }
})
.icon {
    height: 35px;
    width: 35px;
    display: block;
}
<head>
<link rel="shortcut icon" href="https://abs.twimg.com/favicons/twitter-pip.ico" type="image/x-icon">
<link rel="icon" href="https://www.youtube.com/s/desktop/6e57b52d/img/favicon_48x48.png" sizes="48x48">
<link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196">
</head>

<input name="search" type="text">
<span class='icon'></span>

【讨论】:

    猜你喜欢
    • 2014-01-24
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多