当网页上的任何元素被点击时触发js函数 [英] triggering js function when any element is clicked on the webpage

查看:629
本文介绍了当网页上的任何元素被点击时触发js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Chrome扩展,在那里我想传递网页上点击的元素传入一个js函数,它将计算出css选择器。



i我无法知道如何在网页上点击任何元素时触发js函数。 添加一个事件您的内容脚本中的侦听器会检查用户点击,捕获目标元素,然后使用chrome.runtime.sendMessage将数据发送到您的后台页面或其他目标目标。

content.js

  document.addEventListener('click',函数(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:内容脚本和后台页面通信,

background:{
scripts:[ background.js]

},

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


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
}

这篇关于当网页上的任何元素被点击时触发js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆