简体   繁体   中英

How to simulate key presses in JS

I wish to click on an <img> and make the browser simulate the typing out of a variable + [ENTER]. This should basically simulate the same thing that would happen if a scanner scanned a barcode

I'm developing an add-on for a webapp that we use at work. This work includes needing to scan barcodes which I've gotten to show on screen and we can scan, however in some instances it has proven to be a little difficult to scan. I'd like to be able to click on the barcode that is generated and have it simulate keystrokes. The characters don't need to end up in any input field as I assume the webapp is set to capture keystrokes for the whole window. I just need the keystrokes to be entered pretty fast to simulate a barcode scanner.

The jsfiddle provided currently has the variable being sent to an input field but that is not necessary for the final results.

I'd like to keep this vanilla javascript as I'm still learning it and don't wish to move on to Jquery until i have my feet firmly planted in JS.

https://jsfiddle.net/pshock13/o2gtzaj5/215

document.getElementById('barcode').addEventListener('click', function() {
      //this is where I want theBarcode to be typed out + [ENTER] automatically.
      main_input.value = theBarcode;
    })

You can simulate a keypress by dispatching a KeyboardEvent for keydown and keyup .

Eg simulating keypresses for your barcode:

document.getElementById('barcode').addEventListener('click', function() {
    main_input.value = theBarcode;

    [...theBarcode].forEach(function(c) {
        window.dispatchEvent(new KeyboardEvent('keydown',{'key':c}));
        window.dispatchEvent(new KeyboardEvent('keyup',{'key':c}));
    });

    window.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'})); 
    window.dispatchEvent(new KeyboardEvent('keyup',{'key':'Enter'}));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM