获取 url 的图标并显示它(firefox web-ext)

Get the favicon of a url and display it (firefox web-ext)

我正在开发 Firefox web-ext。有没有办法让我获得当前 website/tab 的图标。我提到了 this 但我不认为 %c 有效 anymore.This 是我的 manifest.json (部分):

"permissions": [
  "storage",
  "<all_urls>",
  "tabs",
  "activeTab"
],

"browser_action": {
  "default_icon": "icons/love.ico",
  "default_title": "Show URL and Favicon",
  "default_popup": "popup/addsite.html"
}

addsite.js 文件如下所示:

var addnewsite = document.querySelector('.addnewbutton');
var siteContainer = document.querySelector('.site-container');
addnewsite.addEventListener('click', addNEWsite);

function onError(error) {
  console.log('Error: ${error}');
}//generic error handler

function addNEWsite(){
    siteurl();
    function siteurl(){
        browser.tabs.query({ currentWindow: true, active: true }, function (tabs) {
            addurl(tabs[0].url);
        });
    }
    function addurl(link){
        var urltostore = link;
        var gettingItem = browser.storage.local.get(urltostore);
        gettingItem.then((result) => {
            var objTest = Object.keys(result);
            if(objTest.length < 1 && urltostore !== ''){
                storeurl(urltostore);
            }
        }, onError);
    }
}

function storeurl(link){
    var storingurl = browser.storage.local.set({link});
    storingurl.then(() => {
        displayurl(link);
    }, onError);
}

function displayurl(link) {
    var url = document.createElement('div');
    var urlDisplay = document.createElement('div');
    var urlPara = document.createElement('p');
    url.setAttribute('class','url');
    urlPara.textContent = link;
    urlDisplay.appendChild(urlPara);
    url.appendChild(urlDisplay);
    siteContainer.appendChild(url);
}

这是单击扩展中的按钮 (picture) 时的快照。您可以看到我可以使用当前代码获取 url。但我还想在其 url 旁边显示页面的图标(favIconUrl 显示图标的 url,我可以从那里获取它吗??,如果可以,如何获取?)。谁能帮我做这件事?

可以通过以下两种方式之一找到网站的图标。在 <head> 部分,您可以找到:

<link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />

href 属性指向网站图标的位置。如果缺少它,那么它将始终位于网站根目录中的 /favicon.ico。

对于那些需要代码的人,这里是:

var favicon = document.createElement('img');
// get the url of favicon using favIconUrl function
favicon.src = "https://jsfiddle.net/favicon.ico";
document.body.appendChild(favicon);
// you can also append it to a container if you want to

查看 fiddle 了解此内容。

要获取网站图标的 url,可以在末尾附加 /favicon.ico 或从 favIconUrl.

中获取

https://icons.better-idea.org/ 为 less 和 less favicon 存储在域的根目录这一事实创建了解决方案真是太棒了。

它是免费的,它可以工作(到目前为止我的情况是 100% 的时间)并且尽可能简单:

<img src='https://icons.better-idea.org/icon?url=github.com&size=80..120..200' />

如果您不想依赖可以随时停止的免费网络服务(正如他在网站上正确指出的那样),您可能需要为 github 存储库添加书签 https://github.com/mat/besticon

拍手拍手

编辑 2022

开发人员不再保留服务器来托管此服务,您必须自己托管它:

https://github.com/mat/besticon#hosting