From popup.html, how do I run a javascript function with the onclick button?

advertisements

I'm trying to build an extension for Chrome, but I'm a newbie and I'm having trouble understanding the Docs provided by Google. I want the extension to have a popup that shows a few buttons, and when a button is clicked, I want to run a script.

This is my setup:

popup.html

<button id="test1" onclick="getSite();">button 1</button>
<button id="test2" onclick="getSite();">button 2</button>

content_script.js

function getSite(){alert('getSite works!');}

I'm having trouble understanding how to use the chrome javascript api, as I see others saying use chrome.tabs.executeScript, but I can't figure out where that line goes. Can anyone help me? I'll give you a cookie! or just an upvote.. or maybe both?


I think you are having this problem because of restrictions imposed by the Google Content Security Policy. It mentions that iniline javascript like the one that you have mentioned in you code will not be executed. Try removing the onclick="getSite()" from your HTML markup to content_script.js. Use addEventListener function to attach the event to the button.