Azharkamar.com

Automatic Redirect to Mobile Website using JavaScript

Snippets
17 Mar 2012
3 comments

Developing a Mobile site? Want users to be automatically redirected when they access it from a mobile device? Well I think I’ve got a nice piece of JavaScript that will do just that.

But firstly I’d like to mention that as far as possible, do it the responsive way using the HTML5 and CSS3 media queries.

I believe every awesome developer would recommend the HTML5 Boilerplate so check out this HTML5 Boilerplate + FlexSlider template I made.

Now let’s take a look at the script that will automatically redirect a user to the mobile version of the site when he’s on mobile.

Wait, demo first.

Use a mobile device to view the demo! Like duh, you already knew that right.

View Demo

Mobile Redirect JavaScript Snippet

This script was adapted from Local Streamer (thanks dude) and then modified to handle the case where users want to view the desktop site after redirected to the mobile site.

Here’s an overview of what this snippet does:

Instructions

  • Copy the script below and paste it in the default index file of your desktop site before the </head> tag.
  • On line 5, the code refUrl.substr(7, 16) will simply remove the first 7 characters and then return the next 16 characters of refUrl.
  • 7 is the amount of chars in http:// so don’t change this number unless your mobile site is using some other protocol. 16 is the number of characters in m.azharkamar.com so you’ll have to change this number accordingly. Here’s a string counter for people who don’t like counting.
<script>
//<![CDATA[
    var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
	var refUrl = document.referrer; // Get the URL where the user came from
	var prevUrl = refUrl.substr(7,16); // Create a substring after 'http://' and '.com'
        var mobileUrl = "m.azharkamar.com"; // String from mobile site URL; must match prevUrl

   // Run auto-redirect only if the user is on mobile and isn't from m.azharkamar.com
   if ((mobile) && !(prevUrl == mobileUrl)) {
        document.location = "http://m.azharkamar.com";
    }
 //]]>
</script>

Author - Azhar Kamar
3 Comments Revolving around this Article
  1. Ben

    Hey, I’m having the same problem, have you managed to find a fix for this? Works great otherwise!

    Thanks
    Ben

  2. Will

    Hi,

    Same as Alex – I’m getting stuck in a loop. Thank for this though!

  3. Alex

    Hello! Thank you for the scrip, it’s great! But I’ve had a little problem. If a put a link in the bottom of the page for the desktop version, I get stuck in a loop and I don’t know how to solve this problem. Could you help me? Thank you

Write a Comment! NOW! :)

Current ye@r *