How to replace onclick event with GreaseMonkey?

greasemonkey, javascript

Solution

Actually, deleting the `onclick`s is not at all an onerous task.

With jQuery, the code would merely be:

$("span.thumb a").prop ("onclick", null);

Or, for older versions of jQuery:

$("span.thumb a").removeAttr ("onclick");

A complete script:

// ==UserScript==
// @name     _Kill select onClicks
// @include  http://YOUR_SERVER/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==

$("span.thumb a").prop ("onclick", null);

The advantage of this approach is that: (1) You preserve `PostMenu.click()` in case you want it, or it's needed, elsewhere, (2) You are removing crud from the page, which makes it just a little bit less unwieldy. (3) I suspect that you might also need to unwrap or modify that link -- in which case, the targeted rewrite approach using jQuery is the way to go.

If you really just want to replace the `PostMenu.click()` function with your own empty function, the code for that is just:

unsafeWindow.PostMenu.click = function () {};

As for having Greasemonkey intercept all `onclick` events... That is not easy to do reliably. Forget that approach unless there is an overwhelming need for some reason (which there doesn't seem to be, in this case).

Problem

This website has a gallery of images. Each time I click on a thumbnail image it opens the URL in a new tab (not because I set firefox to open links in new tabs). I want to just open the URL in the same window. An example of what the thumbnail images looks like is this. ``` <span class="thumb" id="789"> <a href="/post/image/12345" onclick="return PostMenu.click(12345)"> <img class="preview" src="http://abc.com/image.jpg" title="title" alt=""> </a> </span> ``` I believe that `onclick="return PostMenu.click(12345)"` is doing this. How can I replace the `PostMenu.click()` function with my own empty function in GreaseMonkey? Is there a way to make a GreaseMonkey script intercept all onclick events? My only other option is to go through all the `span` classes and remove the `onclick="return PostMenu.click(12345)"` from the link tags. But since there can be over a hundred of these on a single page, I'd rather not do that.

Original source