简体   繁体   中英

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.

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:

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).

I would be grateful if anyone can point me in the right direction.

EDIT:

This is my popup.html file:

<!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.

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