cjmling
cjmling

Reputation: 7278

Create a button click handler for any page

I am trying to make a Chrome extension. My goal is to do the following:

  1. To run a certain JavaScript when a button or link with specific id is clicked.
  2. That button or link with specific id could be on any web site.

My code looks really simple but I am not sure where I am missing. Will the jQuery not work this way in Chrome extension? Is there any equivalent code in plain JavaScript?

manifest.json

{
  "name": "Handle a button click",
  "version": "1.1",
  "background": { "scripts": ["background.js"] },
  "permissions": [
    "tabs"
  ],
  "browser_action": {
      "name": "click to handle"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["jquery-1.9.0.min.js"]
    }
  ],
  "manifest_version": 2
}

background.js

$(document).ready(function(){
    $("#my_submit").click(function(){
        alert("yo");
    });
}

UPDATE AFter debugging for background.js I am seeing:

"Uncaught ReferenceError: $ is not defined"

jQuery file is not getting included? or why?

Upvotes: 1

Views: 738

Answers (1)

Mathlight
Mathlight

Reputation: 6653

Try this:

$(document).ready(function(){
  $(document).click(function(event){
    if(event.target.id == "my_submit"){    
        alert("yo");
    }
    });
});

This checks al the click events if the element that fires the click event has id my_submit and if so, alert

jsfiddle

Upvotes: 1

Related Questions