简体   繁体   中英

What is the reliable way to detect OS using Javascript?

The use of navigator.userAgent is not advised as per MDN. In my application I want to have a shortcut for del key.

In mac del key (is backspace) with charCode = 8. In windows del key charCode = 46.

I want to treat both keyEvents same. I am currently using userAgent but it is unreliable as that property can be spoofed. I am wondering what is the best way to know the client OS otherwise.

More deprecated navigator properties navigator.appVersion navigator.platform

/* code objective */
if ((keycode == 8 && os == 'macintosh') || keycode == 46) {
    //This is keyboard shortcut to perform delete
}

Relying on KeyboardEvent.metaKey and KeyboardEvent.Backspace solved my problem

Full Key Values - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

For more details refer: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#Key_values

Thanks to @Teoli2003 for twitter reply - https://twitter.com/Teoli2003/status/663995373766221824

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