在网页上单击任何元素时触发 js 函数

triggering js function when any element is clicked on the webpage

本文关键字:js 函数 元素 网页 单击 任何      更新时间:2023-09-26

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

我无法弄清楚在网页上单击任何元素时如何触发 JS 函数。

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

内容.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)

背景.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." );
});