ruby-on-railsrubydevice-detection

Detect screen size and pixel density on the server-side?


I've been doing some research and I think I know the answer already, but I'm wondering if there's any means by which you can get a device's screen size and pixel density without the use of javascript or relying on CSS3 media queries.

Essentially, I'm looking into what it would take to get the screen resolution and pixel density so that the server could decide which image to server in a URI request.

So far I've not found anything that says this is even possible but I thought hey, why not ask?


Solution

  • I don't agree entirely with the above correct answer. Realistically this answer is correct in many cases...but theoretically it is not. Often requests made to a web server contain a User-Agent field which could, in theory, be used to discern information about device screen resolutions and properties.

    Web requests do not pass through the client first. They pass to the server, which then serves a page to the client so the server gets the request first...Ruby on Rails, for example, receives a request through an action controller to a resource and then serves a page to the response.

    Look at an example UA parser such as : https://github.com/visionmedia/user-agent

    A sample user agent being sent by my computer is:

      User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like  enter code here`Gecko) Chrome/17.0.963.83 Safari/535.11
    

    I think it is eminently possible to make a good guess what my screen resolution (DPI etc) is given that information via a server. You would, of course, need a table of device information to reference.

    For mobile devices it gets even easier. If the User-Agent is a mobile safari for iPad:

      Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML,   like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10
    

    You can know with strong certainty what the screen resolution is on the server. You can even know the height and width of the browser with that info. I suspect the same is true with many mobile devices such as Android or Win Mo.

    So in summation, I agree its impractical to do this but I also disagree.

    I believe Facebook has undertaken a major project cataloging devices and screen resolutions and made it open source because they faced similar issues when creating the facebook mobile app e.g. they had to catalog all the discrepancies between all mobile browser renderers so they could tailor the client app to every individual case. Perhaps that project might have the necessary information to do this...in theory.