How to redirect the site when it is a mobile?

5

I have the following code that should work, but in mobile it does not work in the chrome browser:

var permitir_mobile = true;
var mobileUrl = 'http://m.meusitemobile.com.br';

$(document).ready(function() {
    var e = window;
    redirectIfWidthLargeSize(e);
    $(e).resize(function() {
        redirectIfWidthLargeSize(e);
    });

});

function redirectIfWidthLargeSize(e) {
    if ($(e).width() < 1024 && permitir_mobile == true) {
            e.location.href = mobileUrl;
    }
    if ($(e).width() < 1024) {

        var el = '<li class="mob-url"><a href="' + mobileUrl + '">Versão Mobile</a></li>';

        if ($('#menu_horizontal_base ul li.mob-url').length != 1) {
            $('#menu_horizontal_base ul li:last').before(el);
            $('footer nav ul li a').css('padding','30px 8px');
        } else {
            $('#menu_horizontal_base ul li.mob-url').remove();
        }
    }
};

It's interesting that if you do that on my cell phone screen, it shows 980 , that is, it's less than 1024 :

$(function() {
   document.write('<p style="font-size:120px">'+$(window).height()+'</p>');
});

Then it should redirect in the condition below, but it is not what is happening:

 if ($(e).width() < 1024 && permitir_mobile == true) {
     e.location.href = mobileUrl;
 }
    
asked by anonymous 28.07.2016 / 14:34

3 answers

6

You have two options:

  • detect whether it is mobile or not
  • detect the width of the screen with .matchMedia

The first is simple, just detect if the userAgent exists the string Mobi :

if (navigator.userAgent.match(/Mobi/)) location.href = ...

or using technology that only exists on mobiles / pads:

if(typeof window.orientation !== 'undefined') location.href = ...

If you choose to check the screen width you can do this:

var mobile = window.matchMedia("only screen and (max-width: 760px)");
if (mobile.matches) location.href = ...
    
28.07.2016 / 15:12
2

I've done this and got it this way, this can be in <head> to not waste time processing other things before it will (can) be redirected, nor need jquery:

redi_width = 1024;
if(window.innerWidth < redi_width) {
    window.location.replace(mobileUrl);
}

window.onresize = function() {
    if(window.innerWidth < redi_width) {
        window.location.replace(mobileUrl);
    }
};
    
28.07.2016 / 14:41
1

Based on Sergio's response, I'll post here how I solved the problem:

 function redirectIfWidthLargeSize(e) {
    var w = $(e).width();
var mobile = e.matchMedia("only screen and (max-width: 1024px)");
    if (typeof e.orientation !== 'undefined' && mobile.matches && navigator.userAgent.match(/Mobi/) && origin != 'web') {
        e.location.href = mobileUrl;
    }
};

I used this to test and it worked:

<script src="https://code.jquery.com/jquery-3.1.0.min.js"integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="
  crossorigin="anonymous"></script>
<script>
$(function() {
    var origin = 'mobile'; // quando for 'web' não irá redirecionar 
    var redirect = 'não', directUrl, e = window;
    var mobile = e.matchMedia("only screen and (max-width: 1024px)");
    if (mobile.matches && (navigator.userAgent.match(/Mobi/) ||
        typeof e.orientation !== 'undefined') && origin != 'web') {
        redirect = 'sim';
    } else {
        origin = 'web';
    }

    if (e.location.search) {
       directUrl = e.location.search.replace('?','');
    }

    var redirected = (directUrl == 'mobile') ? true : false;

    if (redirect == 'sim' && !redirected) {
       e.location.href='?mobile';  
    }

    var redirecionou = (directUrl) ? 'sim' : 'não';
    $('#teste').html('largura tela: ' + $(e).width() +
                 ' redirecionará: ' 
                 + redirect + 
                 ' - versão: '
                 + origin + 
                 ' - redirecionou: ' 
                 + redirecionou +
                 ' - url de redirecionamento: ' + directUrl);
});
</script>
<div id="teste" style="font-size:45%;"></div>

But another persistent problem that prevented the script from executing and stopping the redirection was viewport that was not configured correctly for mobile versions, generating an error of type warning , as I solved the problem: / p>

 <?php if ($this->device == true || $origin == 'web'): ?>
     <meta name="viewport" content="user-scalable=yes, initial-scale=0.333" />
 <?php else: ?>
     <meta name="viewport" content="initial-scale=0.5, maximum-scale=1" />
<?php endif; ?>
    
28.07.2016 / 16:16