简体   繁体   中英

triggering js function when any element is clicked on the webpage

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.

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM