点击网页任意元素触发js函数

triggering js function when any element is clicked on the webpage

我正在编写一个 chrome 扩展程序,我想将在网页上单击的元素传递给一个 js 函数,该函数将计算 css 选择器。

我无法弄清楚如何在网页上单击任何元素时触发 js 功能。

在您的内容脚本中添加一个事件侦听器,用于检查用户点击、捕获目标元素,然后使用 chrome.runtime.sendMessage 将数据发送到您的后台页面或其他目标目的地。

content.js

document.addEventListener('click', function(e){
    var target = e.target || e.srcElement;
    var attributes = Array.prototype.slice.call(target.attributes).map(function(i)    {
        return [String(i.name)+": "+String(i.value)]
    })

    chrome.runtime.sendMessage({method:"captureElement",data:attributes});   
},true)

background.js

chrome.tabs.onActivated.addListener(function(tabId, changeInfo, tab) {
   // alert(changeInfo.url);
   chrome.tabs.executeScript(null, {"file": "content.js"});
});

var container = []
chrome.runtime.onMessage.addListener(function(message){
  if(message.method == "captureElement"){
    container.push(message.data)
    alert(message.data)
  }
})

manifest.json

 {
 "name": "stack practice",
 "version": "1.0",
 "description": " content script and background page communication",

 "background": {
    "scripts": ["background.js"]

  },

   "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"]
 }],
  "permissions": [
    "http://*/",
     "contextMenus",
     "activeTab"
],
  "manifest_version": 2
}

您可以使用事件参数目标 属性,像这样:

document.body.addEventListener('click', function (e) {
    console.log(e.target);
});

请参阅 MDN: Event.target

中的完整说明

您可以创建一个函数并在单击任何元素时调用它,将元素 ID 作为参数传递,在获取元素的 ID 后您可以做任何您想做的事情。

点击div内的简单代码将给出警告消息-

事件处理程序可以绑定到任何 <div>:

<div id="target">
Click here
</div>
<div id="other">
Click here
</div>

$( "#target" ).click(function() {
alert( "target div is called." );
});