How to detect the screen DPI using JavaScript

<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
    dpi_x = document.getElementById('testdiv').offsetWidth;
    dpi_y = document.getElementById('testdiv').offsetHeight;
</script>

Then you can use JQuery to send dpi_x and dpi_y this to to your server

http://jsfiddle.net/sxfv3/


In webkit you can detect if your user has a so called "high dpi screen" by simply retrieving the value from:

window.devicePixelRatio

Normal dpi screens will return 1. The iPhone 4 will return 2, but numbers like 1.8 or 2.12 are also possible.


There is, so far, no standard and supported-everywhere solution.

window.devicePixelRatio, as suggested by laurens peeters, does work if you don't care about IE, or any browser from the ancient times, like early January 2013 (e.g., Firefox 17).

See Cross Browser Retina/High Resolution Media Queries (and various comments and links there) for how to get this information as of late 2012, but you'll have to keep searching again, and adjusting your code, every so often until something finally gets standardized, and implemented in every browser, with widespread-enough version adoption that you can stop caring about older versions…