How do I redirect the site when it’s a mobile?

Asked

Viewed 1,248 times

5

I have the following code that should work, but on mobile does not work in 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();
        }
    }
};

Interesting is that if you do this on the screen of my phone, it shows 980, that is, it is less than 1024:

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

So he should redirect in the condition below, but that’s not what’s going on:

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

3 answers

6


You have two options:

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

The first is simple, just detect if in Useragent there is the string Mobi:

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

or using technology only available on mobiles/pads:

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

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

var mobile = window.matchMedia("only screen and (max-width: 760px)");
if (mobile.matches) location.href = ...
  • Interesting, I’ll test this last one...

  • I’ll put to test any of the cases, it has to roll.

  • I found that the problem I’m having is lower, I’ll have to study one more in my code.

2

I already did that and I got it this way, this can be right in the <head> not to waste time processing other things before since it will (may) 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);
    }
};
  • But I would like to understand why mine is not working? Can you tell me?

  • what is the difference of window.innerWidth and window.width ?

  • @Ivanferrer window.width() does not exist in native javascript: http://www.w3schools.com/jsref/prop_win_innerheight.asp

  • @Ivanferrer I tested your code and in mine it works

  • Hello @Miguel, has the screen.width, It’s true, I got confused.

  • Exactly, you can use this if you want to @Ivanferrer

  • I’ve been searching @Ivanferrer, apparently screen.width() gives us the length of the monitor, not the browser window (browser): https://helpx.adobe.com/analytics/kb/comparing-browser-width-height-and-resolution.html ... http://www.w3schools.com/jsref/prop_screen_width.asp

  • Just adding that window.matchMedia(mediaQueryString) only works in IE from version 10.

Show 3 more comments

1

Based on Sergio’s response, I’m going to publish here how I managed to solve 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 it 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 problem that persisted, which prevented the script from running, and stopped redirecting, was the viewport which was not configured correctly for mobile versions, generating a type error warning, how I solved the problem:

 <?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; ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.