triggering js function when any element is clicked on the webpage

馋奶兔 提交于 2019-12-10 23:21:46

问题


I am writing a chrome extension where i want to pass the element clicked on the webpage to be passed into a js function which will calculate the css selector.

i am not able to figure out how to to trigger the js function when any element is clicked on the webpage.


回答1:


Add an event listener in your content script that checks for user clicks, capture the target element, and then use chrome.runtime.sendMessage to send the data to your background page or other target destination.

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
}



回答2:


You can use event parameter target property, like this:

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

See full description at MDN: Event.target




回答3:


You can create a function and call it when clicked any element, pass the element id as an argument and after getting id of the element you can do whatever you want.

Simple code when clicked inside a div will give an alert message-

The event handler can be bound to any <div>:

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

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


来源:https://stackoverflow.com/questions/35620119/triggering-js-function-when-any-element-is-clicked-on-the-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!