Chrome扩展程序无法选择DOM元素

时间:2018-11-02 12:08:38

标签: javascript jquery html google-chrome-extension

我想编写一个Chrome扩展程序,以对单击页面上的特定元素做出反应(此类页面的示例:https://www.mentimeter.com/s/ea1639a1b16e623b9c7b4bc884f86aae/cc3aaa4bae22)。

我真正感兴趣的特定元素是<rect>元素,但是为了简单起见,我提供了此演示,它演示了我可以使脚本对单击高水平{{ 1}}元素,但不是其子元素<div id="root">(请参见图像中页面元素的列表)。

page elements shown by Chrome dev tools

对于我如何选择DOM中其他元素的任何线索,我将不胜感激。如果我将其输入到Chrome开发工具中的javascript控制台中而不使用扩展名,则用于选择<div class="application mm-ui">元素的jQuery代码可以正常工作。

除了manifest.json和content.js之外,扩展文件夹还包括jQuery 3.3.1的下载副本(名称:“ jquery.js”)。

(我想还有一种方法可以使页面从googleapis下载jQuery,但我还没有设法找出方法。一次只能做一件事。)

manifest.json

<div class="application mm-ui">

content.js

 {
  "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/*"]
  }]
}

等待。还有更多。

令人困惑的是,使用香草JS的简单版本可以毫无问题地选择$(document).ready(function(){ //$("div#root").click(function(){//works $("div.application").click(function(){//does not work alert("click"); }); }); 元素:

manifest.json

<rect>

content.js

{
  "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/*"]
  }]

1 个答案:

答案 0 :(得分:1)

如评论中所述:

使用@wOxxOm建议使用的jQuery事件委托。

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

或者如果您不想使用事件委托,请使用此易于使用的mutationObserver库github.com/uzairfarooq/arrive