Skip to content
Advertisement

Browser Extension’s creating dynamic buttons with dynamic links

I’m trying to create a browser extension popup (in JS) that creates a number of buttons with links that open up different webpages. The function takes a number of parameters, the main one being b_link which is an array of URL’s to the website. For some reason, only the last URL in array is applied to all of the buttons that are created.

I’m not entirely sure what the problem is, I could speculate but I don’t think that would be productive. One thing I did notice and had to compensate for was using b_link in the lambda function. Just using b_link[i], the lambda function only saw undefined so no webpage opened, but using var tmpLink = b_link[i]; at least gets the link into the function and allows a webpage to open.

How should I make these buttons so that they all have their own links, rather than only the last one in the array?

The function in question:

function createSiteButton(numBtns, b_id, b_class, b_text, b_link, b_bg)
{
    
    // check if the input text is an array
    if (Array.isArray(b_text))
    {
        // create the new set of buttons
        for (i= 0; i < numBtns; i++)
        {
            var newButton = document.createElement('button');
            var tmpLink = b_link[i];
            newButton.id = b_id;
            newButton.class = b_class;
            newButton.innerHTML = b_text[i];
            newButton.style.background = b_bg;
            
            newButton.addEventListener("click", function()
            {
                if (tmpLink)
                {
                    window.open(tmpLink, "_blank");
                }
            });
            
            button_array[i] = newButton;
        }   
        
        // add the new buttons the screen
        for (i= 0; i < numBtns; i++)
        {
            divID.appendChild(button_array[i]);
        }
    }
}

Advertisement

Answer

I found a way to do this via creating an a element, setting href via a.href = tmpLink and appending the button to the a element as a child. The final function is:

function createSiteButton(numBtns, b_id, b_class, b_text, b_link, b_bg)
{
    var outputElem = document.getElementById('output');
    
    // check if the input text is an array
    if (Array.isArray(b_text))
    {
        //var tmpLink = null;
        // create the new set of buttons
        for (i= 0; i < numBtns; i++)
        {
            var a = document.createElement('a');
            var newButton = document.createElement('button');
            var tmpLink = b_link[i];
            newButton.id = b_id;
            newButton.class = b_class;
            newButton.innerHTML = b_text[i];
            newButton.style.background = b_bg;
            
            a.href = tmpLink;
            
            a.appendChild(newButton);
            divID.appendChild(a);
            
            button_array[i] = newButton;
        }
    }
}
Advertisement