Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension unable to select DOM element

I want to write a Chrome extension that reacts to the clicking on a specific element on a page (example of this type of page: https://www.mentimeter.com/s/ea1639a1b16e623b9c7b4bc884f86aae/cc3aaa4bae22).

The specific element I really am interested in is a <rect> element, but for the sake of simplicity I provide this demo which shows that I can get the script to react to the clicking on a high-level <div id="root"> element but not its child <div class="application mm-ui"> (see listing of page elements in image).

page elements shown by Chrome dev tools

I would be grateful for any clue as to how I can select other elements lower down in the DOM. The jQuery code for selecting the <div class="application mm-ui"> element works fine if I enter it into the javascript console in Chrome Dev Tools instead of using the extension.

The extension folder includes a downloaded copy of jQuery 3.3.1 (name: "jquery.js") in addition to the manifest.json and the content.js.

(I guess there is also a way to make the page download jQuery from googleapis but I haven't yet managed to find out how. One thing at a time.)

manifest.json

 {
  "manifest_version": 2, 
  "name": "Mentimeter demo",
  "version": "0.1.0",
  "description": "Mentimeter demo",
 "content_scripts": [{
      "js": ["jquery.js","content.js"],
    "matches": ["https://www.mentimeter.com/*"]
  }]
}

content.js

$(document).ready(function(){
//$("div#root").click(function(){//works
$("div.application").click(function(){//does not work
alert("click");
});
});

Wait. There's more.

The puzzling thing is that a simpler version using vanilla JS manages to select the <rect> elements without problem:

manifest.json

{
  "manifest_version": 2,

  "name": "Vanilla JS selection demo",
  "version": "0.1.0",
  "description": "Vanilla JS selection demo",

  "content_scripts": [{
    "js": ["content.js"],
    "matches": ["https://www.mentimeter.com/*"]
  }]

content.js

document.addEventListener("click",function(event){
var target = event.target;
if(target.tagName.toLowerCase() == "rect"){
alert("rect clicked");
} 
},false);
like image 426
danbae Avatar asked Sep 11 '25 14:09

danbae


1 Answers

As discussed in the comments:

Use what @wOxxOm has suggested use jQuery event delegation.

$(document).on('click', 'rect', function() { ...... }) 

or use this easy to use mutationObserver library github.com/uzairfarooq/arrive if you don't want to use event delegation.

like image 144
elegant-user Avatar answered Sep 13 '25 04:09

elegant-user