0

So I'm trying to make an extension that runs a script when a submit button is pressed. Since Google Chrome extensions cannot have the scripts directly inside the HTML for security reasons, I need to have an external script. How do I call a function from an external script with the submit button?

This is what I've tried so far:

Here's the popup.html:

<html>
    <head>
        <!--css styling removed from here-->
        <script src="popup.js"></script> 
    </head>
    <body>
        <!--html page is working fine, only the button is not-->
        <input type="submit" value="Submit" onclick="convert();">
        <p id="p2">Value</p>
    </body>
</html>

(I've also tried calling popup.convert(); , but that doesn't work either)

And here's the popup.js:

function convert(){
    document.getElementById("p2").innerHTML = "Hello!";
}

I'm trying to change the p element in my extension popup, not the webpage.

Thanks in advance!

EDIT: It was suggested that my question was a duplicate of this: onClick within Chrome Extension not working

That didn't really help, although it did give me a link to https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution which was semi-helpful.

The problem with the solution on the other question is that it is not a button but a link. (Thanks for pointing me to that topic anyway!)

Community
  • 1
  • 1
  • @Teepeemm That's a link, not a button though. –  Sep 30 '15 at 17:24
  • 1
    it does not matter than it's a link. You're trying to add an event handler - you can't do that inline. – Xan Sep 30 '15 at 17:37

1 Answers1

1

HTML is a markup language and contains only the markup:

<input id="convert-submit" type="submit" value="Submit">

The script should attach events to the elements once the popup document body is loaded (you reference the script in <HEAD> so it's executed when the <BODY> hasn't been parsed yet):

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("convert-submit").addEventListener("click", convert);
});
wOxxOm
  • 43,497
  • 7
  • 75
  • 96
  • I moved the script reference into the body and edited the code to your code, and it still isn't working. Maybe the problem also lies within `document.getElementById("p2").innerHTML = "Hello!";` –  Sep 30 '15 at 17:30
  • It is working, here's a [sample extension](https://puu.sh/ktJyR/82baeac1bc/popup.crx), you may load it manually by drag'n'dropping the downloaded file onto chrome://extensions page. – wOxxOm Sep 30 '15 at 17:35
  • I got your code to work on my end, I'm going to check my code again. Thanks! –  Sep 30 '15 at 17:38
  • I got it to work by renaming the p2 element to p. I forgot the I needed to make an id for the p element. Thanks for your help! –  Sep 30 '15 at 17:48