Question

I want to use a userscript to automatically click on a button when a page is loaded.
The target page's HTML (which I do not control) looks like this:

<a id="signInBtn" alog-alias="qb-signin-btn" class="signInBefore btn btn-24-white grid" data-disabled="false" hidefocus="hidefocus">
    <em><b>CheckIn</b></em>
</a>

It is a strange link without an href attribute. I am trying to use this code:

var btn = $("a#signInBtn");
btn.trigger("click");

But Chrome's console gives me this:

Error in event handler for (unknown):
Error: Syntax error, unrecognized expression: a[href^=/i?]

How can my userscript click this button?

Was it helpful?

Solution

jQuery .trigger() is mostly only good for events set by jQuery. And, in this case, it must be called using the target page's instance of jQuery, not the userscript's. (Also, how is your script using jQuery? The wrong method can bust the page, the script, or both.)

There may be other events required and/or AJAX to contend with, we can't tell from your question. See Choosing and activating the right controls on an AJAX-driven site.

Polling for the node and triggering mouse event(s) will work in almost all cases. Here's a complete userscript to get you started:

// ==UserScript==
// @name     _Auto-click the sign-in link
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_addStyle
// ==/UserScript==

var signInTimer = setInterval ( function() {
        var signInBtn = document.querySelector ("#signInBtn");
        if (signInBtn) {
            clearInterval (signInTimer);

            var clickEvent  = document.createEvent ('MouseEvents');
            clickEvent.initEvent ('click', true, true);
            signInBtn.dispatchEvent (clickEvent);
        }
    }
    , 200
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top