Code Snippet

Home » Code Snippets » JavaScript » Redirect Mobile Devices

Redirect Mobile Devices

<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "mobile.html";
}
//-->
</script>

"mobile.html" would be replaced with the location of wherever your mobile version resides. This technique could be adapted to load an alternate stylesheet as well.

For iPhones/iPods Specifically

<script language=javascript>
<!--
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
   location.replace("http://url-to-send-them/iphone.html");
}
-->
</script>

Subscribe to The Thread

  1. anon

    Nice and concise! thanks

  2. Thanks a lot @anon. I find it very useful also.

  3. no safari

    • Jonathan

      Works just fine with Safari on iphone for me, if you are using safari on a desktop you’ve got bigger problems.

    • Works Great

  4. What if mobile phone can not use JavaScript?

    • Did you ever get an answer to your question? I have the same concern.

      Reuben

    • pcacesam

      USE PHP!!! :D

      I use this

      you’ll have to change the extension on your page from .html or .htm to .php so the server knows to process the script. Also this needs to be before the <html tag – ie the first line on the page. To add a device just add it to the if statement under the mobileDevice() function

    • pcacesam

      function mobileDevice()
      {
      $type = $_SERVER['HTTP_USER_AGENT'];
      if(strpos((string)$type, “Windows Phone”) != false || strpos((string)$type, “iPhone”) != false || strpos((string)$type, “Android”) != false)
      return true;
      else
      return false;
      }
      if(mobileDevice() == true)
      header(‘Location: http://www.m-tek.biz/mobile.html‘);

  5. Fernando Sanches

    But and devices that do not work with javascript?

    • Hello World

      Most devices now-a-days do have javascript capabilities.

  6. in the iPad/iphone version.

    Is it suppose to say…
    “navigator.userAgent.match(/iPod/i” or
    “navigator.userAgent.match(/iPad/i” ????

    • It says iPod/iPhone version, no iPad at all

    • Maithili

      What about javascript for rails application as it is not working for mobile application?

  7. Nate Paul

    This works great!

    One thing: Once a mobile user logs onto the site it takes them to the mobile site. I want to let them be able to go to the full-version site. But of course when they click on the link, it redirects them to the mobile site.

    Any help is appreciated!

    • You ever get an answer back on this? I was wondering the same thing.

    • Geoffrey Freedom

      Why don’t you just clone the non mobile site(w/out the javascript mobile redirect) and make it index1.html and make that the link from the mobile site?

    • I used the clone methed(by geoffrey Freedom) and it works great, I only did it for the home page so “index1.html” has no flash so the handhelds can display the images I use with jquery if they use the full site.

    • Google penalizes for duplicate content, so when cloning your index (or any page) may want to create a mostly new way to write the page content.

    • Gavin

      for the clone website you can just add the no follow meta tag on the clone. that way google won’t penalize you.

    • Set a cookie.
      Interaction w/ the cookie can save the value of if the user wants the mobile or full site, or simply the presence of can be used to continue the function or die.

      Wrap your switcher in a if/then statement, and if the user chooses to go to the full site, it sets the cookie and reloads. The reload will run through the if/then switcher, but by adding a line to check if cookie exists, that means if it does then the user opted IN for the full site and OUT of mobile, sending to mobile sheets or mobile site stops right there, no duplication of content, saves your google ranking and to undo the no-mobile, they simply clear the cookie. No cookie? Then the user detection runs, picks mobile or full until the user decides otherwise.

      Its kind of cobbling old school to new school, but it does let you set a reference point per user without building a whole redundant site for a what if situation…

    • If you have not managed to get round this yet. To get round the looping caused by this problem, you need to clone the index.htm file and name the new file index1.htm. Then the latter page is the point of destination when the full web button is pressed.
      SIMPLES!!

    • I think cloning the index has other issues. I find the best simple solution (without messing with cookies) is to set another if statement within the script

      if &ltscreen.width &lt= 699) {
      if (document.referrer.indexOf(‘mobile.html’) == -1){
      document.location = “mobile.html”;
      }}

      In english that’s

      “if the screen width is less than 699px,
      and I am not already coming from the mobile page,
      send me to the mobile page”

  8. No more Mobify? You should do a post on mobile sites ;)

  9. thanks you men !!!!!

  10. Outstanding… a simple, elegant solution… thank you…

  11. dimsen

    How to include android phones?

    • works fine with android phones.

    • Marcus

      May have to make a small modification… what with the Galaxy Nexus as well as any forthcoming Android phones that have 720p resolution screens. The above code in the OP would wind up directing a GNex user to the desktop version of the site I reckon. As nice as 720p resolution is, the screens themselves are still far too small to make desktop site viewing a pleasant experience on a phone.

  12. Good article,
    also maybe try to check out my script called “redirection_mobile.js”. It detects the User Agent and redirects to a mobile version if you’re accessing a site from a mobile device.

    In some case you want to redirect from a mobile device to a desktop version (like with a link “Go to the main site”), the script will handle that and once you finish your session, you’ll access to the mobile version again.

    You can find the source code on github here https://github.com/sebarmeli/JS-Redirection-Mobile-Site and you can read more details in one of my article here:

    http://blog.sebarmeli.com/2010/11/02/how-to-redirect-your-site-to-a-mobile-version-through-javascript/

    • Thanks for the code. I’ve already tried this with an iPhone 4 and it works great but, for some reason, it’s not working on a HTC Desire HD – it just goes straight to the full site. Is there a fix for this? Thanks!

    • Woo hoo!

      Thanks for posting the link. I tried the solution on css-tricks and it worked great. But your js solution gave me the greater control that I needed for linking back to the full version of the website.

      Thanks!

  13. hi its very cool thanks buddy

  14. Raden Mas Purwandharu

    how about for blackberry solution..
    thanks in advance.

  15. sebas

    Thank you very much!!!

    Ive been searching for this code all day!!:D

  16. great thanks

  17. Once changed to window.location it worked! Thanks!

  18. Nice. Thanks this worked on my iPod but not on the iPad.

    iPads are ok for regular sites because the screen is big enough.

    Can someone list which mobile devices this script works on?

    Thanks.

    • It works on any device with a screen width below 699 pixels. This includes iPhone/iPod 4g with retina display. You can adjust the 699 to a higher number, but I would not because of old monitors with a 700 width.

      If you are targeting iOS devices, you can use the second one, editing

      if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

      to

      if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || navigator.userAgent.match(/iPad/i))) {

      By standards, it works on any device with a screen width below 699, and JavaScript enabled. But there are always exceptions. (Like CSS3 in IE6, for example).

    • steve

      Hey Mooseman,

      I tried swapping in your code for this to work on ipads, but when I did dreamweaver told me that there was a syntax error on the edited line. Any suggestions as to how I could fix that? Thanks so much.

      Steve

  19. is this redirect seo friendly

    after implementing this for a mobile site

    my Google ranking went down and i am wondering if this affected my seo

  20. SIrish

    As I understand it, the code is on the full-screen site, it just redirects, so the phone doesn’t have to use java.

  21. Awesome trick! Thank you, i’ll use it on my tumblr blog. :)

  22. Can any one have idea to solve through .httaccess?

  23. Hi,

    How to redirect …desktop/page1.html to …mobile/page1.html, …desktop/page10.html to …mobile/page10.html…etc…for more than 300 pages.
    So not just to …mobile/index.html

    Thanks for your help

  24. If you redirect via the Location object you will lose the HTTP referrer from the original request. This means all of your mobile traffic will appear as direct traffic in your analytics.

    I think server-side detection is preferred. Some options:
    http://detectmobilebrowser.com/
    http://wurfl.sourceforge.net/

  25. Thank you so much! Works perfectly and so simple!!!

  26. Jonathan

    Very nice work on this! Took me a lot of searching but this is what we needed.

  27. Tregenza

    That’s so helpful, thank you!

  28. JavaScript doesn’t work at all… so I decided to use the .htaccess file to redirect mobile devices.

    http://stackoverflow.com/questions/3680463/mobile-redirect-using-htaccess

    Consider, if someone doesn’t want to redirect to the mobile version of your site implement a “Regular Site” button on the mobile version.

  29. Thank you so much for this javascript code!

  30. Amit Jadhav

    Thank You so much for provide dis easy code :)

  31. i would choose media querries…so i can handle it with css and i dont need a 2nd (?) website with the same structure & (maybe)content :-)

  32. a good server-side (php) script about this application can be found at

    http://code.google.com/p/php-mobile-detect/

    • Eneko

      isAndroid(), isBlackberry(), isOpera(), isPalm(), isWindows(), isGeneric()…

      and the isIOS mode?

  33. Awesome, thanks so much for this, helped me tons !!

  34. Need a script like this for a client. Works perfectly. now they can have just the tools from our site in a mobile device rather than the whole site. Love it.

  35. Thanks for a quick, simple solution!

  36. Wonderful code, thanks for the tip…

  37. Andrew

    I pasted the code, and when I load the page on my iPod touch, i get “Page Not Found”…any suggestions?

  38. Great script — thanks

  39. Natalie

    I can’t tell you how happy I was that this actually worked the first time I tried it, thanks for making my life so much easier!!!

  40. Thanks! Great script, simple solution, love it.

  41. Cucho

    Another solution using php can be:

    <?php
    if(strstr($_SERVER['HTTP_USER_AGENT'],’iPhone’) ||
    strstr($_SERVER['HTTP_USER_AGENT'],’iPod’))
    {
    header(‘Location: http://www.domain.com/iphone‘);

    exit();
    }
    else if(strstr($_SERVER['HTTP_USER_AGENT'],’iPad’))
    {
    header(‘Location: http://www.domain.com/ipad‘);

    exit();
    }
    else{
    header(‘Location: http://www.domain.com/web‘);

    exit();
    }

    ?>

    You can add “else if” alternatives for other user agents. Of course it works in servers with php support.

    Regards.

  42. Great script. I’ve been using it for a couple of weeks and it works for everyone that has used it, but for one. He has an iPhone 4 and it keeps giving him the old landing page. The script isn’t redirecting him.

    I asked if his javascript was turned off and he said no. The odd thing was the link worked for him earlier. I wonder if his cache, cookies or history are screwing him up?

    Has anyone had any problems like this before?

    The site is http://www.criticalpr.com

  43. If I have a home for iPhone, a home for Droids and a home for computer browsers, in order to send visitors in one of three directions, do I insert the script like this:

    <!–if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { location.replace(“http://url-to-send-them/iphone.html”);}–>

    <!–if (screen.width

    ??

  44. fabien egot

    When I’m trying to add Android, my iPad is not redirected anymore.
    My code is:

    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
    {
    location.replace(“iphone”);
    }
    else if(navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))
    {
    location.replace(“ipad”);
    }

    Any idea ?

    • thankU


      else if(navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))

      It’s error.

      else if((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/Android/i)))

  45. César

    You saved my life! Thank you!!

  46. This technique is very intuitive, but a PHP detect/redirect is more efficient. Check out the following site for a complete detect/redirect, and option to view full site:

    http://www.squidoo.com/php-mobile-redirect

  47. Dave

    This is an odd one, but is there a way to do the reverse. I’ve built a mobile site and I want to direct people if they land on this URL to another site.

  48. Dave,

    You can redirect using .htaccess. I am kinda confused about what you are trying to do though. Are you wanting to redirect everyone that lands on your mobile page to another site??

  49. Dave

    I’ve built a site using WordPress that is only for mobile users. Because of the contract with the festival…I need to send desktop users to the main website and not the mobile one I created.

    I guess if I don’t advertise the URL it won’t matter anyway, and they can direct mobile users from there site to mine.

    But I guess regardless I’d like to have nobody viewing the mobile site that I created on a desktop.

    Dave

  50. You saved me! This is just how great, for me as a “non-developer” this was awsome, when i just “launched” the mobilesite for our event! Thanks again!

  51. Jewell

    just what i was looking for …….

  52. this works great… but how can i re-direct users back to the main site from their mobile devices if they want to see the desktop web version of the website? thanks.

    • Set a cookie when they visit the mobile site, and check for the cookie prior to the redirect.

      A complete solution for redirect/ view full site using php can be found at the following:
      http://www.squidoo.com/php-mobile-redirect

    • Thanks Matt… this php script is very glitchy. I implemented everything properly, but sometimes it directs to the mobile site, other it just doesn’t. Also, it seems like the only way to redirect from Mobile to Full site is by making the link with http://www.yoursite.com// with double slash at the end (weird, not sure why)…
      One question: in the link you provided, the article mentioned this line of code:

      setcookie("mobile","m", time()+3600, "/");

      Where should I put that?
      Thanks a lot.

    • That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.

    • That goes on your mobile page. It sets the cookie to bypass the mobile redirect when you want to view full site.

    • I have not seen it acting glitchy. The code you are talking about should be placed on the mobile index page. That is the PHP code that will set the cookie to override the mobile redirect when you try to view your full site.

  53. Best way i found is;

    //

  54. Nice little script. Where in the document do you place this js? in the head or in the body or wherever you want?

    • Anywhere…

    • I would think that this JS would go in the head, before any full-site CSS and content, therefore redirecting before loading unnecessary files. That can be slow on mobile and take up valuable KB transfer.

      I have a slightly different solution that I will post here tomorrow. It’s a different take on this awesome snippet but ads a little helper for a request that people have been asking for.

      Cool stuff CHRIS, thanks !!

  55. This is the best javascript mobile redirect I have found. It’s rather perfect and handles all the cookie, redirect to and fro the mobile and full site. And does it with screen width like your above script does.

    https://github.com/miohtama/detectmobile.js

  56. i am asking doubt about the “slide to unlock”.i want the page to redirect to another page after the unlocking
    soory for asking this the thread for unlocker was closed that’s why asked here

  57. i fixed it ,
    can anyone tell me how to make the slider to left side?please

  58. Ernie

    this seems a bad approach – you either force your mobile user to a site that is a subset of your main site, and they can’t do anything about it, or you put this snippet in every page and every new page to re-route to a mobile equivalent? Just botu workable for a small site I guess but otherwise look at something else.

  59. John

    Basic question: How do I manage and update a mobile subdomain so that the user can have the optionality of switching back and forth between the mobile and desktop version of the site? In other words, what is the best way to ensure that the content remains the same on both sites, and only the layouts change? Or do I have to manually update and upload the desktop site, then manually update and upload the mobile site?

  60. Brendan Mullins

    i like my take better :D

    
    function browsercheck(){
            var b=navigator.userAgent.toLowerCase();
    	namen=["android","iphone","mobile"];
    	for(var c=namen.length,a=0;a<c;a++)
    		if(-1<b.indexOf(namen[a].toLowerCase()))return!0;return!1
    };
    
    browsercheck()?
    	alert('mobile')
    	:
    	alert('not mobile')
    ;
    

    in the array “namen” you can add as many types as you want, as long as any of the names are somewhere in the UserAgent of the devices Browser it will return true

  61. Do you have to convert this to .js I get data base error.

  62. Here is more in-depth Javascript solution, provided as a library:

    detectmobile.js

    Read the documentation for answers for some of the posted questions.

  63. Works great: I have tried it on the following page: http://www.muqstuff.weebly.com an dit redirects perfectly but what if you want the code to activate before the page loads? For me, the page first loads and then redirects, is there anyway to get around this?

  64. We’re a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable info to work on. You have done a formidable job and our whole community will be thankful to you.

  65. Hi all i am new here and
    everyone is talking about redirect to the mobile website
    but what if i want to redirects Visitors when they try to view your WebApp or mobile site on a PC.
    i want pc users that go manualy
    from http://www.mobile.domainname.com
    to http://www.domainname.com
    can anyone do that?
    thanks

  66. Keen to give this script a go.

  67. Just what I was looking for..thanks! :o)

  68. Kristi

    Is there a solution for Blackberry devices that can’t show flash?
    I used this code and it worked great for Iphone but not on
    older Blackberries..
    Any help would be greatly appreaciated..

    Cheers

  69. Damian

    This is a great option, but I have a question. How do you deal with users clicking a link on the mobile site to view main site? At the moment this would just end up re-directing them back to the mobile version

  70. you need to duplicate the home page and remove the detection
    Script from it and have the mobile users that wants to see the full site go to it.

  71. This technique could be adapted to load an alternate stylesheet as well.

    Hi! no one seem taking about this option, is there an example somewhre??

    Thank you!

  72. Hello,

    I seem to have the script work on the android device, but on the iphone it goes to the same url of the android js. Has anyone else have this happen to them? It seems like the
    Android code Is being read and the

    User Agent code is not being read by iphone at all. Any ideas?

    Thanks

    • Also just noticed that when i use firefoxes User Agent switcher that the iphone 3 works..i know its a firefox addon but does that mean iphone 4 has a different user agent?

  73. Michael

    I’m not a coder but I pretend to be. I found the script very useful for a project I had. Now I have something similar, but instead of redirecting all mobile devices to the same mobile site I need to redirect them different sites based on the mobile device’s os. An iPhone would go to an iPhone site and an Android would go to an Android site. Any help would be greatly appreciated.

  74. Tusko

    thank you… great post!

  75. CR James

    awesome thanks! (you just ended a 5 hour headache!!) worked great!!!

  76. This is a useful script. Does this work for most smart phones?

  77. This is a good script too bad you only have it available for iphone/ipod. Please expand to blackberry and android, thank you!

  78. I used the script above in my header.php file for my wordpress site and it is redirecting to my mobile site perfectly.

    Now, exactly, how do I get the mobile users to go to the desktop version, if they want to, without it continuously looping back to mobile site? Alot of useful information from others is posted above, I am sure, but for someone as “green” as me, it isn;t helping because I do not know which file to change, etc.

    What I need is a way to switch mobile users (m.mydomain.com) back to desktop site (mydomain.com), if they choose to, without it redirecting in a loop back to mobile site all the time.

    Thank you for the help!!!

  79. Maë

    Hi,

    I plan to use the wordpress/blog url of my website to easily create a mobile version of my dreamweaver website, using a plugin). Can I then type “/wordpress ” instead of “mobile.html” to redirect mobile users to the WP mobile site, as below?

    <!–
    if (screen.width

  80. Hey all,

    I’m utilizing the original script to run a mobile redirect and it works fabulously except I can’t figure out how to get it to redirect to a subdomain, rather than an html file in the main domain. The document location line doesn’t seem to work when the document is located in a subfolder (ie: mobile/index.html)

    Help please? I’m assuming its a simple fix.

    #notacoder

    I’m attempting to utilize the following version of the script.

    <!–
    if (screen.width

  81. Hi Mae, yes, directing it to /wordpress will work just fine.

  82. Sorry to ask again, but I could really use the help…

    I used the script above in my header.php file for my wordpress site and it is redirecting to my mobile site perfectly.

    Now, exactly, how do I get the mobile users to go to the desktop version, if they want to, without it continuously looping back to mobile site? A lot of useful information from others is posted above, I am sure, but for someone as “green” as me, it isn’t helping because I do not know which file to change, etc.

    What I need is a way to switch mobile users (m.mydomain.com) back to desktop site (mydomain.com), if they choose to, without it redirecting in a loop back to mobile site all the time.

    Thank you for the help!!!

  83. Fabri_

    Hi you all.
    This code doesn not work on my web site … or with my LG Android ….
    Someone would please write some URLs where it is working properly, just to check …

    Thanks

  84. I think avoid Using browser javascript redirection for mobile website better to use a HTTP Server Redirection its better to avoid page loading time

  85. thanks everyone, I had seen the code at http://detectmobilebrowsers.com/ but wasnt sure it was good, after reading this thread I tried it and it worked! I wanted my mobile peeps to be able to break out of the mobile site and see the full site if they wanted, and all other solutions either had them stuck on the mobile or I had to make everyone land on a page to make a choice between mobile and regular, including computer people. this was a great solution! Computers go to my full site, mobile people to to the mobile site, and I have links from one too so everyone can choose to go see the other version if they want…

  86. Thanks, smart and simple!

    One mistake not to make is to put the IF statement inside an a document load. The problem this caused was that if you were to use the back button on certain phones you would end up on the main site with no document.location change so the user can’t get back to the mobile.

    Basically I added the code into the main site javascript file inside the document.load which caused this error. Then I removed the document.load wrap and everything was peachy.

    Thanks! :D

    • Hi Mark,

      You just described the problem I am trying to solve. Can you be a little more descriptive with how you solved it. I am a novice at best and am searching for an easy solution. Thanks!

      Matt

    • Define easy :-D

      So when a user lands on the desktop version I would run the above resolution IF statement in-line, so there is no “$(document).ready(function(” surrounding the code. So you would place the above code simply at the top of your webpage. or in your javascript file like this

      
      $(function(){
            if (screen.width <= 699) {
                   document.location = "mobile.html";
             }
      });
      

      But in my setup is is slightly different. Once the user is on the mobile sub domain I have used jquery.cookie.js to configure the rest of the process as sub domain to main domain cookie access is allowed but main domain to another main domain is not.

      If a user would actually prefer to view desktop version they would click on “view desktop version” which would create a cookie with name:mobile value:off. Then be redirected to the desktop domain. The final check done on this domain would be another IF statement run inline checking if the cookie exists and has value “off”.

      
      if (screen.width <= 699
         ) {
      		if( $.cookie("mobile") != null ) {
      			//alert('cookie is here');
      			//alert($.cookie("mobile"));
      		 }
      
      		else {
      			//alert( $.cookie("mobile") );
      			//alert('cookie is not here');
      			document.location = "http://mobileversion.mydomain.com/";
      		}
         }
      

      I have to stress that I would use responsive layouts if possible to save duplicating content/work load but this was not an option for the project I was doing.

  87. Hi,

    I’m using this to test a proof of concept I have it working for iPhone, Android and Windows Mobile. Has anyone figured out a blackberry solution?

    Thanks,

    • Hello Joe

      I was using the following script but not sure what models this works on (this was for a mobile site I built so long ago it was in tables!! :-P) so you will need to do some testing but you get the idea.

      
      var deviceBB = "blackberry"
      var uagent = navigator.userAgent.toLowerCase();
      var cssFile = "handheld.css";
      if (uagent.search(deviceBB) > -1) {
      window.location = 'blackberry-home.html'; }
  88. Will this work for pages that have been “iframed” by Facebook? I ask because, at this time, Facebook tabs (pages inside a facebook page) will not resolve on mobile devices. Each Facebook tab has a unique url. But when using a mobile device, Facebook redirects those urls to the facebook log in page; after the user logs in, a facebook “page not found” error is shown. I would like instead for the mobile user to be redirected out of facebook to a clone-ish page that would display. Anyone have any experience with this?

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~