44

What is the best cross-browser and cross-platform way to detect hardware keyboard presence with javascript?

15
  • 3
    Can you have the user press a key that doesn't exist on a touchscreen keyboard? Like anything that uses Ctrl or Alt?
    – millimoose
    Commented Sep 18, 2013 at 19:03
  • 3
    @millimoose nuh uh
    – Brian
    Commented Sep 18, 2013 at 19:04
  • 2
    Aaanyway. XY Problem. What are you ultimately trying to accomplish? Why do you need to detect this? Give us a little context.
    – millimoose
    Commented Sep 18, 2013 at 19:08
  • 1
    You know the facebook chat? You send messages simply by pressing "Enter", I have to show users that do not have a keyboard button to replace the "Enter" key. Commented Sep 18, 2013 at 19:16
  • 4
    a good design is consistent, show the button to everyone. why assume people know about [enter] anyway? more ways to do stuff usually means more productivity. you can dbl-click a windows title bar to nmaximize it, or you can use a key combo, or the maximize icon, or the top-left window menu, or the taskbar context menu, etc. nobody complains that there are too many ways to maximize...
    – dandavis
    Commented Sep 18, 2013 at 20:25

6 Answers 6

23

This may be an old question, but a few months ago, I was looking for a solution to this myself. I was building a messaging system which should send the message when someone hits Return on their physical keyboard, but inserts a newline when someone hits Return on a virtual keyboard. The way I solved it was by counting the time between keydown and keyup events and getting the average when Return was hit.

I finally got around to documenting it on my blog here.

5
  • 2
    Very clever, I ended up using this solution in my own application. Thank you! Commented Dec 21, 2018 at 2:14
  • this is very clever
    – DaveAlger
    Commented Apr 11, 2019 at 20:27
  • 4
    This is a reliable solution with one major dependency: the user needs to type something first. The holy grail is to reliably detect whether the user has only a software keyboard when the user lands on the page, before they do any typing.
    – thdoan
    Commented Jun 25, 2022 at 1:10
  • This won’t work if the user switches from a virtual keyboard to a physical (or vice versa) while the app is open – I think on tablets this is a realistic issue. Would be pretty hard for the user to figure out what’s going on – especially if the page was open for a long time (say, an installed PWA).
    – felixbade
    Commented Mar 13, 2023 at 12:06
  • Is there an npm package for this? Commented Oct 15, 2023 at 22:00
13

Could you try the theoretical opposite? Instead of trying to detect keyboard hardware, why not try to detect a touch screen? With the ontouchstart event;

if ('ontouchstart' in document.documentElement) {
    // show icon
}
4
  • 28
    And if a PC has a touch screen? Commented Sep 18, 2013 at 19:45
  • 5
    Well, what would you do if an iPad has a keyboard attached to it? It sounds like a lot of code to show a simple icon.
    – bmorenate
    Commented Sep 18, 2013 at 19:47
  • 1
    Many blackberry devices have both touch screen and physical keyboard
    – Anonymous
    Commented Dec 7, 2017 at 12:14
  • I assume many touch-screen PCs may have an issue with this, but at least it is a way to detect some of the newer iPads (which previous Regex check solutions do not seem to work with, specifically in the mobile Safari browser), so +1 for the creative solution
    – Broper
    Commented Aug 31, 2022 at 18:34
4

Keyboard in JS is accessible via browser APIs which delegate to OS APIs and it's not possible to tell if there's a physical keyboard. I can cut the cord off of my physical keyboard right now, turn on virtual keyboard, click on the on-screen buttons with my mouse and the browser will still trigger every keyboard event the scripts are listening to. Form browsers's/JS's perspective the virtual keyboard is indistinguishable from a physical one.

And what does "presence" even mean? If I have a phone with a touch screen and slide-out keyboard do you expect the browser to trigger some kind of "keboardIn"/"keyboardOut" event? Same with cable plug-in/out? :)

If your app absolutely requires a physical keyboard just inform/ask the user.

Edit - after clarification by OP:

You know the facebook chat? You send messages simply by pressing "Enter", I have to show users that do not have a keyboard button to replace the "Enter" key.

So just make a form with text input and listen to the input/form events. Most (every?) soft keyboards have some kind of "Done", "Ready" or similar button. You don't need to know if the "keyCode" is equal to "13", but detect that the user has an intent to submit what he has typed. Or, as the last resort, detect f the device i touch-enabled and display the button then. ( if('ontouchstart' in document.documentElement)/* show touch sbmit button */ )

1
  • 2
    I am making a game that by default uses keyboard to control, but I want to detect if there is no keyboard present so I can put on screen controls.
    – Pete
    Commented May 10, 2018 at 18:08
4

When a virtual keyboard pops up on the screen on a mobile device, the height of your application reduces in order to accommodate the virtual keyboard. So, what you can do is that you can add an event listener that checks whether the screen has resized as the user focuses on the input field.

You can add this functionality using the resize event listener when the input field is focused:

const inputField = document.querySelector(".my-input");

const virtualKeyboardDetected = () => alert("Virtual keyboard detected!");

inputField.addEventListener("focusin", () => {
    window.addEventListener("resize", virtualKeyboardDetected )
})
inputField.addEventListener("focusout", () => {
    window.removeEventListener("resize", virtualKeyboardDetected )
})
2

Use keyboard event to detect if the user have keyboard or not (he/she may press it). Save it in localStorage and the browser will remember it for the next time.

var app = this;
app.hasKeyboard = false;
this.keyboardPress = function() {
    app.hasKeyboard = true;
    $(window).unbind("keyup", app.keyboardPress);
    localStorage.hasKeyboard = true;
    console.log("has keyboard!")
}
$(window).on("keyup", app.keyboardPress)
if(localStorage.hasKeyboard) {
    app.hasKeyboard = true;
    $(window).unbind("keyup", app.keyboardPress);
    console.log("has keyboard from localStorage")
}
1
  • 5
    This won't tell you what kind of keyboard it is (hardware or virtual) Commented Apr 9, 2021 at 19:52
-11
if (confirm('Do you have hardware keyboard?')) {

} else {

}

Edit according to description in comments under question:

What about support 'Enter' everytime and add 'Send' icon only for touch screens (What's the best way to detect a 'touch screen' device using JavaScript?) and as a 'hover' pseudoclass for mouse?

7
  • 1
    But can you imagine if every page facebook asked "Do you have hardware keyboard?" :D Commented Sep 18, 2013 at 19:09
  • 4
    No, but you can do it once and store it in cookie. Commented Sep 18, 2013 at 19:22
  • 1
    It is uncomfortable, even saving it to a database, if the user logs first from pc and then to phone? It is not a good solution... Commented Sep 18, 2013 at 19:26
  • 3
    Yes maybe uncomfortable, but I would recommend you to study something about HTTP cookies, then you will know that cookies are unique per browser. Commented Sep 18, 2013 at 19:34
  • 5
    Ironically this might be the most viable approach here 😂
    – akst
    Commented Apr 21, 2019 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.