How to use input/textarea focus as a condition for hotkeys

Solution 1:

The deepest AutoHotkey (AHK) can detect within Google Chrome, related to web content, is the Chrome_RenderWidgetHostHWND1 control. This control is the viewport for web content. Our input and textarea HTML elements are a little deeper, inside the DOM of the rendered content.

So, we need to find a way to communicate through this wall between the HTML elements and AutoHotkey. Luckily, there is a player on the same side as the HTML who can speak AHK's lingo: JavaScript!

How so? To put it simply, JavaScript can perform an action when an element gains or loses focus. One of these actions can be changing the page title. This in turn changes Google Chrome's window title, and AHK can read window titles!


Setup:

  1. Install my InputFocusTitleChange.user.js userscript. (Source)

  2. Now you can use following syntax in AutoHotkey:

    SetTitleMatchMode, RegEx
    
    #x:: ; normal hotkey
         ; do something
        return
    
    #IfWinActive, \[AHK\] - Google Chrome$
        #x:: ; input/textarea focus hotkey
             ; do something
            return
    
    #IfWinActive
    

Demonstration:

When an HTML input or textarea element has focus, the userscript appends [AHK] to the page title, changing Google Chrome's window title.

window titlegoogle chrome

AHK can use this characteristic, if the window's title ends in "[AHK] - Google Chrome" or not, to indirectly connect HTML input/textarea focus with a set of commands.


Notes:

From my testing, there are two issues:

  1. If the input/textarea is already focused when the page loads, [AHK] may not be added to the page title. You have to move focus away from the element and then back to get the title to change.

  2. If the input/textarea element is dynamically generated after the page loads (this is also when the script loads), then those elements will not have any effect.

I will continue to work on this solution. If you have any suggestions or know of a way to counter these JavaScript issues, please feel free to let me know and/or contribute. The source is posted above and hosted on Github.