2

I am currently using this code from this answer

var ratio = window.devicePixelRatio || 1;
var w = screen.width * ratio;
var h = screen.height * ratio;

It works on desktop firefox, but not on my android browsers (stock or chrome on my Samsung Galaxy S5 phone updated to android 5). I get 320x640 instead of 1280x1920.

Is there a reliable solution to detect screen sizes accross all devices & browsers? I need screen width of device, not inner/client widths or something else.

If it's not possible, several comments saying this is not possible from influential SO members would work fine - I could show this as proof to my client.

Community
  • 1
  • 1
Marko Avlijaš
  • 1,579
  • 13
  • 27
  • check [this file](https://github.com/tysonmatanich/GetDevicePixelRatio/blob/master/getDevicePixelRatio.js) which might be a potential solution. Haven't tested it myself. This appears also in [this question](http://stackoverflow.com/questions/5063489/how-can-you-get-the-css-pixel-device-pixel-ratio), answer by abhinav sharma. – andreim May 03 '17 at 12:15
  • As far as I have dag, there is no real solution to this problem @MarkoAvlijaš – NoOorZ24 May 03 '17 at 12:31
  • @andreim - this is working on my phone. Are you going to create an answer? – Marko Avlijaš May 03 '17 at 12:36
  • @MarkoAvlijaš I don't feel like creating an answer as I haven't come with anything new other than referencing another answer. If you'd like you can create an answer providing your testing results. That might bring something new to the table and I will be here to upvote ;) – andreim May 03 '17 at 12:56

1 Answers1

1

One solution to fix obtaining of device-pixel ratio is described here:

/*! GetDevicePixelRatio | Author: Tyson Matanich, 2012 | License: MIT */
(function (window) {
    window.getDevicePixelRatio = function () {
        var ratio = 1;
        // To account for zoom, change to use deviceXDPI instead of systemXDPI
        if (window.screen.systemXDPI !== undefined && window.screen.logicalXDPI !== undefined && window.screen.systemXDPI > window.screen.logicalXDPI) {
            // Only allow for values > 1
            ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
        }
        else if (window.devicePixelRatio !== undefined) {
            ratio = window.devicePixelRatio;
        }
        return ratio;
    };
})(this);

Therefore the complete code would be:

var ratio = window.getDevicePixelRatio();
var w = screen.width * ratio;
var h = screen.height * ratio;

NOTE: This solution is referenced also in this question answer by abhinav sharma.

Community
  • 1
  • 1
andreim
  • 3,365
  • 23
  • 21