Abhishek Tripathi
Abhishek Tripathi

Reputation: 1381

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.

Upvotes: 2

Views: 223

Answers (3)

nick
nick

Reputation: 1207

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
}

Upvotes: 3

IRSHAD
IRSHAD

Reputation: 2933

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

Upvotes: 0

Alex.Me
Alex.Me

Reputation: 616

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

Upvotes: 0

Related Questions