'How to run a function from content script, when an injected button was clicked?

I am injecting a button through the content script of my chrome extension like this:

btnHtml += '<button id="btn1" style="background-color: #2c3f82; height: 25px; width: 50px; text-align: center; cursor: pointer; border-radius: 4px; color: white; border: 1px solid rgba(0, 0, 0, 0.8); font-size: 15px; margin: 2px;">someText</button>'
const div = document.createElement('div');
div.className = 'ownSizes';
div.innerHTML = '<div style="display: inline-grid; grid-template-columns: auto auto auto auto; background-color: #1d76ce; border-radius: 8px; padding: 10px;">'+btnHtml+'</div>';
document.getElementsByClassName('_4NtqZU')[0].appendChild(div);

That works fine. Now how can I add a function to the button? Do I have to inject a new js into the page or is there an easier way?



Solution 1:[1]

I think the issue you are having is due to not being able to reach your scope because you're adding the element by injecting strings of html.

Alternatively, you could create the button by using the createElement function to give you an actual node that you can inject into the page.

let btn = document.createElement('button' [, options]);

Then you can bind you click event from the current scope

btn.onclick = //some function

Lastly inject into the page using appendChild as you have in your question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Trav Broad