Dive Into Greasemonkey

Teaching an old web new tricks

4.21. Intercepting user clicks

While rewriting links is easy, you can go one step further and trap every click, anywhere on the page, by using the addEventListener function. (This also traps clicks on links.) You can then calculate what to do: whether to allow the click to “fall through” to the clicked element, or do something else entirely.

Example: Do something when the user clicks anywhere on the page

document.addEventListener('click', function(event) {
    // event.target is the element that was clicked

    // do whatever you want here

    // if you want to prevent the default click action
    // (such as following a link), use these two commands:
    event.stopPropagation();
    event.preventDefault();
}, true);

Note the use of an anonymous function passed as an argument to the document.addEventListener function.

← Redirecting pages
Overriding a built-in Javascript method →