2

I have a bit of JS code (echoed by PHP) that will be put on the top of my web pages. The code should evaluate the window size, and based on that, go to the mobile version or go to the pc version.

But when i loead my page (pc version), the page keeps refreshing. How can i make the refreshing stop?

Here's the code:

$page = $_SERVER["PHP_SELF"];
        echo "<script>";
        echo "function screenSizeRedirect() 
            {
                var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
                var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                if (width <= 960) 
                {
                    window.location = 'http://m.bss21universe.ga$page';
                }
                if (width > 960)
                {
                    window.location = 'http://www.bss21universe.ga$page';
                }
            }";
    echo "screenSizeRedirect();";
    echo "</script>";
EVDE KSP
  • 77
  • 1
  • 7
  • Can you provide context around the snippet? At what point specifically in the page is this being loaded? – Romuloux Sep 26 '15 at 15:34

2 Answers2

2

You are redirecting the page, even if you are on the right one.

So if you load the home page, it then checks to see your screen size. If the screen size is for main, it redirects you to main and we start all over again.

You need to write a check to make sure you aren't redirecting to a page you are already on.

Untested sample below:

$page = $_SERVER["PHP_SELF"];
    echo "<script>";
    echo "function screenSizeRedirect() 
        {
            var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            if (width <= 960  && window.location.href != 'http://m.bss21universe.ga$page') 
            {
                window.location = 'http://m.bss21universe.ga$page';
            }
            if (width > 960 && window.location.href != 'http://www.bss21universe.ga$page')
            {
                window.location = 'http://www.bss21universe.ga$page';
            }
        }";
echo "screenSizeRedirect();";
echo "</script>";

Also, there are more sophisticated ways to check for mobile than screen width, many pure JS or jQuery plugins are available that make mobile detection easy. EG mobile-detect.js

Romuloux
  • 689
  • 1
  • 6
  • 21
1

I think you should set as default the pc view and redirect only if the view is opened from a mobile device.

This can be done in many ways but, in my opinion, this method is the best way to detect the device you're making the request.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location = 'http://m.bss21universe.ga$page';
}
Community
  • 1
  • 1
IlGala
  • 3,043
  • 3
  • 31
  • 46