Listen for keyboard without focused input

Hi

I am developing a WMS application and I need to implement barcode reader functionality. I have the options of using a barcode scanner connected with bluetooth on an Android phone or an Android phone with integrated laser barcode scanner.

The android phone will open chrome browser and access the Cuba application with mobile screen for scanning products.
Is it possible to listen to keyboard press events (generated by the barcode scanner) without having an input focused on?

Kind regards

2 Likes

Hi,

You could implement this as JavaScript extension, see topics:

If we need to catch input in JavaScript connector, we can write it as follows:

window.com_company_demo_web_extension_CatchKeyboardInputExtension =
    function() {
        // Pass user interaction to the server-side
        var connector = this;
        var element = this.getElement(this.getParentId());

        var timer = null;
        var buffer = '';

        var sendBuffer = function () {
            console.log("> Sending: " + buffer);

            connector.charsReceived(buffer);

            buffer = '';
        };

        element.addEventListener("keypress", function(event) {
            console.log("> Received code: " + event.which);

            if (event.key) {
                buffer += event.key;

                if (timer != null) {
                    clearTimeout(timer);
                }

                timer = setTimeout(sendBuffer, 250);
            }
        });
    };

This extension can be registered on the layout of the main window:

public class ExtAppMainWindow extends AppMainWindow {
    @Override
    public void ready() {
        super.ready();

        // catch all input on UI
        Layout layout = unwrap(com.vaadin.ui.Layout.class);
        new CatchKeyboardInputExtension((AbstractClientConnector) layout)
                .setCharsInputHandler(chars ->
                        showNotification("Received text " + chars)
                );
    }
}

See the attached demo: catch-keyboard-input.zip (80.9 KB)

1 Like

This is great!
Thank you Yuriy!