简体   繁体   中英

How can I redirect Desktop Users to one site and Mobile Users to another with JavaScript

I would like that if a desktop user visits my site they are redirected to example.com and mobile users are redirected to m.example.com, I have been told to use this script:

<script>

if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) { 
return window.location.assign("m.example.com"); 
} else { 
return window.location.assign("example.com"); 
} 
} 
</script>

but when I visit my site all I get is a white screen. Is there something wrong with this script? and do I need another script, that handles the user agent or is it all handled by the above script? Thanks in advance.

Try this:

<script>

if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) { 
    window.location.assign("http://m.example.com"); 
} else { 
    window.location.assign("http://example.com"); 
} 

</script>

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