Search code examples
javascriptfirefoxfirefox-addon-webextensions

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


I am working on a Firefox web-ext. Is there a way by which I can get the favicon of the current website/tab. I referred to this but I don't think the %c works anymore.This is my manifest.json (part of it) :

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

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

The addsite.js file looks like this :

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);
}

Here is a snapshot when the button inside the extension is clicked:

(picture).

You can see that I can get the url using the present code. But I also want to show the favicon of the page beside its url (favIconUrl shows the url of the icon, can i get it from there!?, if yes,how?). Can anyone help me out in doing this?


Solution

  • For those who need the code for this, here it is:

    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
    

    Check out the fiddle for this.

    For getting the url of the favicon, one can either append /favicon.ico at the end or get it from the favIconUrl.