[Tip] Injecting keystrokes into a webview

253 views
Skip to first unread message

Dave Smart

unread,
Aug 25, 2016, 10:41:05 AM8/25/16
to DroidScript
Put this in the header of your main HTML file inside the WebView :-

<script>
        function SimKey( keyCode, wait ) 
        {
            dispatchKey( 'keydown', keyCode );
            setTimeout( function(){ dispatchKey('keyup',keyCode); }, wait?wait:0 );
        }
        
        function dispatchKey( mode, code )
        {
            var event = document.createEvent('Event'); 
    event.initEvent(mode, true, true); 
            event.keyCode = code;
            window.dispatchEvent(event);
        }
</script>


Do this in your main JavaScript file to send a SPACE key:-

   web.Execute( "SimKey(32);" ); 


Get more keycodes from here :- http://keycode.info/



Steve Garman

unread,
Aug 27, 2016, 1:04:32 PM8/27/16
to DroidScript
Dave's code is very useful but I find the keycode.info page difficult to access from my phone, so I wrote a little function that will let me choose most keycodes as a string.

//these two are the same
sendKey("\r");
sendKey(13);

//these two are the same
sendKey(" ");
sendKey(32);

//these two are the same
sendKey("w");
sendKey(139);


//pass a numeric keycode or a string
//if a string, the first character is converted to a keycode
function sendKey(code)
{
var skel = "SimKey(#);"
if (typeof code == "string")
code = code.charCodeAt(0);
var cmd = skel.replace(/#/,code);
web.Execute( cmd );
}

Dave Smart

unread,
Aug 28, 2016, 6:28:13 AM8/28/16
to DroidScript
Reply all
Reply to author
Forward
0 new messages