Behnam Rajabnezhad Behnam Rajabnezhad - 10 days ago 6
HTML Question

redirect desktop users to another page and mobile user to the main page

I have a problem with this code.I want to redirect my desktop users to block.php page and dont let them in.

i tested a lot of code and non of them work for me.

at the moment,i found this code.its works perfectly...but there is e tiny problem.

when i check my site with mobile ( ios device )..it keeps reloading

this is the code :



<script>

if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i)) {
window.location.assign("http://example.com");
} else {
window.location.assign("http://example.com/block.php");
}

</script>





what is the problem?

Answer

Assuming this script is running on http://example.com, calling window.location.assign inside of the if block would reload the page. It seems to me like you want to call window.location.assign('http://example.com/block.php') only if the user is NOT on a mobile device.

You could try something like this:

function checkIsMobile () {
  if(navigator.userAgent.match(/iPhone/i)){
    return true;
    } else if (navigator.userAgent.match(/iPad/i)){
      return true;
    } else if (navigator.userAgent.match(/iPod/i)){
      return true;
    } else {
      return false;
    }

  }

if (!checkIsMobile()) { 
    window.location.assign("http://example.com/block.php"); 
}