【问题标题】:triggering js function when any element is clicked on the webpage在网页上点击任意元素时触发js函数
【发布时间】:2016-04-07 05:29:41
【问题描述】:

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

我无法弄清楚当点击网页上的任何元素时如何触发 js 功能。

【问题讨论】:

    标签: javascript google-chrome-extension google-chrome-devtools


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 我试过了,但它不起作用。我添加了你写的文件。
    • 我刚刚创建了一个清单文件并包含了您编写的这两个文件。但它不起作用。
    • 这些不是完整的文件,只是代码 sn-ps 说明了内容脚本如何与浏览器中用户的活动选项卡进行交互,然后将特定数据传递回您的程序。您还需要执行内容脚本。
    • 真的很抱歉给您带来困扰。但我只是初学者,请你解释一下我该怎么做才能让它工作。
    • 我尝试使用编辑后的代码。但仍然无法正常工作。我正在发布我的清单文件。请你解释一下它是如何工作的。 @尼克
    【解决方案2】:

    你可以使用事件参数目标属性,像这样:

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

    MDN: Event.target查看完整描述

    【讨论】:

      【解决方案3】:

      您可以创建一个函数并在单击任何元素时调用它,将元素 id 作为参数传递,在获取元素的 id 后,您可以做任何您想做的事情。

      在 div 内单击时的简单代码会发出警告消息-

      事件处理程序可以绑定到任何&lt;div&gt;

      <div id="target">
      Click here
      </div>
      <div id="other">
      Click here
      </div>
      
      $( "#target" ).click(function() {
      alert( "target div is called." );
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-24
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 1970-01-01
        相关资源
        最近更新 更多