Get button clicked with chrome extension

I want to know how to detect if a button with a certain id is clicked on a webpage with my chrome extension. With my code I have an error saying that my element is undefined. Here is my manifest :

"manifest_version": 2,

"name": "app",
"description": "my app",
"version": "1.0",

"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Changer le background"
"permissions": [


And my popup.js file :

document.addEventListener('DOMContentLoaded', () => {
getCurrentTabUrl((url) => {
    document.getElementById('mybutton').addEventListener('click', function() {
        var script = "console.log('clicked');";
        chrome.tabs.executeScript({code: script});


1 answer

  • answered 2018-01-14 16:06 maor

    your popup.js will not load until the user himself will click on the extension's icon... i think you should change your approach and use a content-script like this:

    document.getElementById('mybutton').addEventListener('click', function() {

    you'll need to update your manifest.json for using a content script, something like that:

    "content_scripts": [
        "matches": ["the url of a page for the script", "the url of another page"],
        "js": ["your_script.js"]