Search code examples
javascriptajaxautomationgreasemonkeytampermonkey

Wait to click a button after appearing on the page with Tampermonkey


There's a button on a web page that I would like to automatically click. The problem is that it only appears on the page once another button has been clicked. I've successfully automated the first click, but I have not been able to automate the second click once that button has appeared.

The following code works when I run it in the console after the button has appeared:

// ==UserScript==
// @name     Soundplate SUBMIT MUSIC Button
// @include  https://play.soundplate.com/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

var TargetLink = $("a:contains('SUBMIT MUSIC')")

if (TargetLink.length)
    window.location.href = TargetLink[0].href

But I'm not quite sure how to run it after the first click has occurred.

I've heard of waitForKeyElements, but I'm not exactly sure how I'd implement it here. That might be the solution. Any and all advice would be deeply appreciated.


Solution

  • // ==UserScript==
    // @name     Soundplate SUBMIT MUSIC Button
    // @include  https://play.soundplate.com/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    
    waitForKeyElements (
        ".btn-lg", click
    );
    
    function click (TargetLink) {
    TargetLink = $("a:contains('SUBMIT MUSIC')")
    
    if (TargetLink.length)
        window.location.href = TargetLink[0].href
    }