简体   繁体   中英

Javascript Redirect Mobile Specific Page

I have a website and a mobile version of that website and I want to use something to redirect users based upon their browser size. At the moment I have:

<script>
if (screen.width <= 1024) window.location.replace("http://www.website.com/")
else window.location.replace("http://m.website.com/")
</script>

This works fine for redirecting to home pages but what about linking to specific pages based on external income sources? For example if someone reads my tweet about my latest blog which is at http://www.website.com/post.php?id=1111 , how do I ensure that mobile users are redirected to http://m.website.com/post.php?id=1111 ?

Try something like this:

var reg = "www.website.com";
var mob = "m.website.com";

if(screen.width >= 1024) {
   if(window.location.hostname != reg)
      window.location.replace("http://" + reg + window.location.pathname + window.location.search)
}
else {
   if(window.location.hostname != mob)
      window.location.replace("http://" + mob + window.location.pathname + window.location.search)
}

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