简体   繁体   English

Chrome扩展程序-如何捕获vanillaJS文档上的点击事件

[英]Chrome extension - How can I capture click events on the document vanillaJS

I'm trying to create my first chrome extension and what I would like to do is have a function run each time the user clicks. 我正在尝试创建我的第一个chrome扩展程序,我想做的是每次用户单击时都运行一个函数。

This is my manifest file: 这是我的清单文件:

{
  "manifest_version": 2,
  "name": "MyName",
  "description": "MyDescription",
  "version": "1.0.0",
  "icons": {
    "128": "icon_128.png"
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [ "activeTab" ],
  "content_scripts": [
    {
      "matches": [ "<all_urls>" ],
      "js": [ "contentscript.js" ],
      "all_frames":  true
    }
  ]
}

I've then created a js file called "contentscript.js" which contains the following: 然后,我创建了一个名为“ contentscript.js”的js文件,其中包含以下内容:

document.addEventListener("click", clickHandler);

function clickHandler() {
    alert("test");
}

I couldn't find much online apart from this post: Chrome extension that captures middle click and replaces URL , however that seems to be using jQuery which I would like to avoid if possible (I tried to modify my project based on the above question to work without jQuery but nothing happens once I load my project to chrome in dev mode and click on the page). 除了这篇文章之外,我在网上找不到很多东西: Chrome扩展程序捕获了中间点击并替换了URL ,但是似乎使用的是jQuery,我想尽可能避免这种情况(我尝试根据上述问题修改我的项目,在没有jQuery的情况下也可以正常工作,但是一旦我在开发人员模式下将项目加载到chrome并单击页面,就什么也没有发生。

I would be grateful if anyone can point me in the right direction. 如果有人能指出正确的方向,我将不胜感激。

EDIT: 编辑:

This is my popup.html file: 这是我的popup.html文件:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" type="text/css" href="popup.css" />
        <!--script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>-->
        <script src="popup.js"></script>
        <title>wow!</title>
    </head>
    <body>
        <div class="main-content">
            <h1 class="main-title">w0w!</h1>
        </div>       
    </body>
</html>

Haven't had time to play with this for a while, but had another look today and found the solution. 有一阵子没时间玩这个,但今天又换了个样子,找到了解决方案。 I was using Visual Studio to write my code, and this created a solution folder withing the folder my code was saved in. So seems that Google extensions don't like having any extra bits in there which caused no code to be run. 我使用Visual Studio编写代码,这创建了一个解决方案文件夹,其中保存了我的代码所在的文件夹。因此,似乎Google扩展不喜欢其中包含任何多余的位而导致没有代码运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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