Doubt - Mobile Site

Asked

Viewed 60 times

0

How can I get the Server to automatically identify that the User is being used by a mobile Device and send it to a mobile site

1 answer

3


If it is Node.js with Express (from what I’ve noticed it looks like it’s what you use) or for the front-end you can then use the:

Node.js/Express:

First install via npm:

npm install mobile-detect --save

Then in your project do something like this:

var MobileDetect = require('mobile-detect');
var md = new MobileDetect(req.headers['user-agent']);

if (md.mobile()) {
    res.redirect('http://mobile.site.com');
} else if (String(req.get('host')).indexOf('mobile.') == 0) {
    //Acaso acessar o site mobile no navegador Desktop ele irá redirecionar para o site normal
    res.redirect('http://www.site.com');
}

Browser/front-end

If you are going to use the browser you can download the mobile-detect.min.js or use CDN, like this:

<script src="//cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.4.1/mobile-detect.min.js"></script>

It should look something like this:

<script src="mobile-detect.min.js"></script>
<script>
var md = new MobileDetect(window.navigator.userAgent);

if (md.mobile()) {
    window.location.replace('http://mobile.site.com');
} else if (window.location.hostname.indexOf('mobile.') == 0) {
    //Acaso acessar o site mobile no navegador Desktop ele irá redirecionar para o site normal
    window.location.replace('http://www.site.com');
}
</script>
  • Thank you, I needed those references, I help us out 2 ways, Hugs.

  • @Marcosgotado please mark the question as correct.

Browser other questions tagged

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