Skip to content
Advertisement

Tampermonkey .click() not working

I’m trying to auto click a button in tampermonkey, but for some reason the code isn’t executing. Though, if I put the code in console and run it, it works fine.

Here it is:

$(document).ready(function() {
    path = window.location.pathname;
    setTimeout(autoTraderReady, 10);
    $('#VehicleApplyButton').click();
});
<table id="VehicleApplyButton" class="x-btn va-apply-button x-btn-noicon x-column" cellspacing="0"><tbody class="x-btn-small x-btn-icon-small-left"><tr><td class="x-btn-tl"><i>&nbsp;</i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i>&nbsp;</i></td></tr><tr><td class="x-btn-ml"><i>&nbsp;</i></td><td class="x-btn-mc"><em class=" x-unselectable" unselectable="on"><button class=" x-btn-text" id="ext-gen147" type="button">&nbsp;</button></em></td><td class="x-btn-mr"><i>&nbsp;</i></td></tr><tr><td class="x-btn-bl"><i>&nbsp;</i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i>&nbsp;</i></td></tr></tbody></table>

Button does not switch dynamically, tried doing an alert when the function runs, doesn’t alert me.

Advertisement

Answer

Given your code:

1. $(document).ready(function() {
2.     path = window.location.pathname;
3.     setTimeout(autoTraderReady, 10);
4.     $('#VehicleApplyButton').click();
5. });

and based upon your comment below, the click on line 4 is expected to trigger an AJAX request fired from a .click listener elsewhere in your document. If this listener exists within an external script, my suspicion is that the other listener is an not around in time to catch the click event you’re triggering. That is to say, it starts listening after your click has already fired.

$(document).ready only waits for only the DOM to load, not external scripts; try changing line 1 to $(window).on('load', function(){...}); instead.

If that fails, try adding following debugging lines:

1. $(document).ready(function() {
2.     console.log( $('#VehicleApplyButton') );
3.     $('#VehicleApplyButton').click(function(e){ console.log( e ) } );
4.     $('#VehicleApplyButton').click();
5. });

Line 2 – confirm #VehicleApplyButton exists

Line 3 – confirm click event is propagating

Note: my first draft overlooked that jQuery interprets .click() as a shortcut for .trigger('click') with no params, rather than the listener .on('click',[data],handler) with 1-2 params. Thanks for the polite correction, @robertklep.

User contributions licensed under: CC BY-SA
11 People found this is helpful
Advertisement