How to replace onclick event with GreaseMonkey?

There is an image gallery on this website. Each time I click on the thumbnail, it opens the URL in a new tab (not because I installed firefox to open links in new tabs). I want to just open the url in the same window. An example of how thumbnails look 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)" does this. How to replace the PostMenu.click() function PostMenu.click() my own empty function in GreaseMonkey? Is there a way to make the 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)" tags from the link tags. But since there can be more than a hundred on one page, I would prefer not to.

+6
source share
1 answer

Actually, removing onclick is not at all a burdensome task.

With jQuery, the code will be simple:

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

Or, for older versions of jQuery:

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

Full 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 save PostMenu.click() in case you want it, or if you need it, in another place,
(2) You remove crud from the page, which makes it a little less cumbersome.
(3) I suspect you might also need to expand or change this link - in this case, the target rewrite approach using jQuery is the way to go.


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

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

As for the fact that Greasemonkey intercepts all onclick events ... This is not easy to do reliably. Forget about this approach if for some reason there is no huge need (which in this case does not seem).

+4
source

Source: https://habr.com/ru/post/914320/


All Articles