php/js results differ on mobile device

Associate
Joined
11 Oct 2008
Posts
268
Hey guys,

I am using this code to use javascript to send the browser window width to a php session variable.

PHP:
session_start();

$parentDir = basename(dirname($_SERVER['PHP_SELF']));;

if (!isset($_SESSION['screenWidth'])) {
    echo '<script>window.location = "' . "/" . $parentDir . "/" . '?width="+window.innerWidth</script>';
    if (isset($_REQUEST['width'])) {
        $_SESSION['screenWidth'] = $_REQUEST['width'];
        header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . "/" . $parentDir);
    }
}

it works fine on my pc, however, when I try it on my phone it returns a width value of 900, which is wrong.
If i add the javascript directly it returns a true value of 350.

Code:
<button onclick="myFunction()">Get Width</button>
<script>
function myFunction() {
    alert(window.innerWidth);
}
</script>

I uploaded a demo: http://www.myprimaryweb.co.uk/checkWidth/

Does anyone have any ideas whats going on? Cheers
 
Works fine for me on my iPhone 6. Returns a value of 980 which is the width of the phone in pixels (both for the readout and pressing the button).
 
Yeah it's working fine on my 6+ and the G5 is fine too.

What phone/OS have you got? I vaguely remember there being an issue with eclair and ICS but I doubt your phone is eclair old and afaik ICS was fixed within a week or two.

Edit: saying that it appears 980px is what safari reports as viewport size but it's actual width 414px is given using screen.width property.

http://www.w3schools.com/jsref/prop_screen_width.asp

Are you after the actual screen size or what it wants to render websites as? If it's the latter I believe your code is correct.
 
Last edited:
Thanks, thats helped a lot. The width is perfect. Its not included this example, but the height is a little out. I think it must be the screen.height taking the toolbars into consideration, so, i'm guessing theres nothing I can do about that :P
 
Erm try;

window.screen.availHeight

Returns 716 rather than 736 for an iPhone 6 guesstimating but the toolbar looks about 20px.

Apparantly its height minus toolbars.

Edit: rather good page you can try live on;

http://ryanve.com/lab/dimensions/

Thinking about it you'll probably need orientation of the device which could be achieved by by checking if window.screen.availHeight > screen.width to see if device is in portrait mode.
 
Last edited:
Back
Top Bottom