Search code examples
javascriptgreasemonkeytampermonkey

Userscript won't un-focus the text input on some pages


I have a small Greasemonkey script which is meant to unfocus everything and just return the focus to the top level of the webpage.
The code looks like this:

document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && event.keyCode === 32) {
        document.activeElement.blur()
    }
}, true);

It works fine on all the web pages I use, except for WhatsApp Web. It immediately refocuses the message typing box.
I have turned autofocus off in Firefox.

How can one ensure that truly nothing is left in focus? Not even the WhatsApp Web message input box.


Solution

  • Are there any errors or messages in the browser console? And what browser version are you using?

    Anyway, without creating a WhatsApp account, or you posting an MCVE, here some possibilities:

    • The page uses JS to reset focus -- triggered by keydown.
    • The page uses JS to reset focus -- triggered by something else.
    • The page has reset the default active element ( (Used to be) possible on some browsers).
    • The page has overridden document.activeElement.blur()

    This code might work:

    document.addEventListener ('keydown', zEvent => {
        if (zEvent.ctrlKey && zEvent.keyCode === 32) {
            let actElem     = document.activeElement;
            if (actElem)    actElem.blur ();
            else            console.error ("document.activeElement is unset");
    
            zEvent.preventDefault ();
            zEvent.stopImmediatePropagation ();
        }
    }, true);
    


    If it doesn't and there are no relevant messages in the browser console, run this from the console:

    console.log (document.activeElement.blur.toSource() );
    

    And see if it's not the native function.

    Another thing you can try is to find or create a different input and .focus() it. (document.body.focus() will often not work, alas.)


    Otherwise, you'll have to find the javascript that's resetting focus and block that. How to do such a thing depends on exactly what the page code is. It's something for a different question but various mechanisms have all been covered on other Stack Overflow questions already.