简体   繁体   中英

How Do You Break A JavaScript Redirect To Mobile?

I have created a simple script that will detect the users device and if that device is mobile than it will redirect to the mobile side. When you are on mobile the site will create a cookie that should essentially break the redirect when you visit desktop again. Below is the code on the main website:

<script>
// simple mobile detection script
// create a variable to store response to user agent queries
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() ||     isMobile.Opera() || isMobile.Windows());
    }
};

// if any of the listed agents are accessing the page, redirect to mobile version with     geolocation enabled
if(isMobile.any()) 
{
    if(jQuery.cookie('mobilea')!== 1)
    {
         window.location="/mobile/";
         console.log('true');
    }
}
</script>

The cookie is successfully being instantiated on the mobile side with the following code:

jQuery.cookie('mobilea',1, {path: '/'});

Any ideas?

if(jQuery.cookie('mobilea')!== 1) will always be false because '1' is not exactly equal to 1 . Either switch to != , or replace 1 with '1' .

if(jQuery.cookie('mobilea')!== '1')

jQuery.cookie('mobilea') is going to return a string and not an integer, so your strict check on it will never be false. If you change it to

jQuery.cookie('mobilea') !== '1'

You can test it properly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM