Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function JavaScript between popup.html and popup.js in chrome extension (taking into account message from Background) [duplicate]

I would like to execute function in chrome extension (in popup.js) by clicking on button in a innerHTML.

My code in popup.html is:

<html>
    <head>
        <script src="popup.js"></script>
    </head>

    <body>
        <div id="panier_container"> </div>
    </body>
</html>

My code in popup.js :

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.text === 'results') {
        var panier_container = document.getElementById("panier_container");
        var texte = "<button onclick=\"toto()\"> TOTO </button>";
        panier_container.innerHTML = texte;
     });
});

function toto() {
    alert("toto");
}

When I execute the code, I see the button "TOTO" but when I click on the button, nothing happen. Out of chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { the button execute the function. But inside no.

like image 958
Jeremy Bergeret Avatar asked Oct 15 '25 15:10

Jeremy Bergeret


1 Answers

I'd suggest attaching the function using JavaScript DOM functions instead of the html onclick attribute. Chrome extensions don't allow inline javascript in the HTML, see this SO question and the Chrome Developer documentation here. What if you gave the button a convenient handle like an id and used .addClickListener() instead?

var panier_container = document.getElementById("panier_container");
var texte = "<button id='totoButton'> TOTO </button>";
panier_container.innerHTML = texte;
document.getElementById("totoButton").addEventListener("click", toto);

function toto() {
  alert("toto");
}

Also worth noting that you might want to move your <script> tag to the end of the <body> or give it an async attribute, because based on the location of the script tag, the #panier_container might not have loaded yet, see the first answer here for an explanation of how the browser interprets script tags.

like image 192
Ananth Rao Avatar answered Oct 17 '25 05:10

Ananth Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!