1

I'm creating my first Chrome extension and the code just seems to not be working. Basically for now, I want the extension to be able to identify a click on an input field and give an alert. I think the extension is not recognizing the click. I've tried multiple things, but here's the most recent code:

manifest.json

{
  "name": "Pi",
  "version": "1.0",
  "description": "Pi works!",
  "permissions": ["activeTab", "declarativeContent", "storage"],
  "browser_action": {
    "default_icon": {
      "32": "pie.png"
    }
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["contentScript.js"]
  }],
  "manifest_version": 2
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    alert('HELLO WORLD!!');
});

contentScript.js

document.addEventListener('DOMContentLoaded', function(){
document.getElementsByTagName('input').addEventListener("click", function (){
  alert("Hi");
});

});
  • What is the expected behaviour? – quant Nov 29 '18 at 00:07
  • I'd like the extension to always keep running in the background and detect whenever a user clicks on an input field on any website. Upon the clicking inside the input field (bringing it to focus), I want it to give an alert. – user10719554 Nov 29 '18 at 00:19

2 Answers2

1

Remove document.addEventListener('DOMContentLoaded', function(){ You actually don't need it. The chrome Browser will decide when to run content script based on run_at settings in the manifest.json default is document_idle. See more here.

GodsArchitect's example is correct for detecting the click event of INPUT tags. However, you may need to consider onFocus event on INPUT tags in case if users use keyboard TAB key to focus into the input field.

const inputTags = Array.from(document.querySelectorAll('input'))

inputTags.forEach(function (input) {
  input.addEventListener('focus', function (event) {
    alert("Hi...")
  }, false)
})
Aefits
  • 3,399
  • 6
  • 28
  • 46
0

The following does the job.

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    if(target.tagName == 'INPUT'){
        alert('You clicked an Input!');
    }
}, false);

Source: https://stackoverflow.com/a/9012576/10383955