Posterous theme by Cory Watilo

Javascript Code Snippet: how to detect all mobile browsers and redirect your visitors to mobile version website

With the adoption of smartphones, most growth in mobile websites adoption will come in the coming years, just now milions users are  accessing internet by smartphones. Let be your website ready to meet such people. In this article we will explain how we have resolved this issue on our website http://www.localstreamer.com .Localstreamer is a software able to search news and events in any city of the earth. The information are retrieved from socialnetwork (facebook, twitter, foursquare,...) and from the engine News "Microsoft Bing" and finally displayed to the user.

The system also offers to all developers the ability to use the free Location API,  for languages: PHP, Object-C, Java (Adnroid too), Python, Ruby , read the tutorial [here]

The mobile version of our website is built on jquerymobile and can be accessed by typing the url http://m.localstreamer.com on your mobile device. What we wanted to do is redirect our visitors from www website to mobile version by using Javascript. First of all we present you the result code, maybe you want it rather to understand how it work, so this is, take it:*

 <script type="text/javascript">// <![CDATA[
    var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
    if (mobile) {
        document.location = "http://www.yoursite.com/mobile.html";
    }
// ]]></script>
 

How it work? Let analyze and explain this simple javascript code in few steps:

1) Detect the browser: the Javascript property navigator.userAgent that return a string object and enables you to detect the name and version of any web browser. An Example result for HTC Droid Incredible with Safari browser, Android 2.2 based can be:  

Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; ADR6300 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17

Do you want a complete browser list? try this: http://www.zytrax.com/tech/web/mobile_ids.html

2) We put the string in lower case by apply toLowerCase() function

3) We search in the navigator.userAgent string the name of some mobile devices iphone|ipad|ipod|android by using the test method.The test() method tests if the string matches a given regular expression. It returns true if it finds a match, otherwise it returns false.

4) If the mobile variable contains true, we redirect the browser to mobile version by using the document.location instruction. It Indicates the URL of the current document in the browser.

If you need to implement mobile browser detection in other languages than Javascript,you can use the MobileESP open source project for PHP, Java, APS.NET (C#), and Ruby. The MobileESP project seeks to provide web site developers an easy-to-use and lightweight API for detecting whether visitors are using a mobile device. http://blog.mobileesp.com/?page_id=2

* !Please read this before apply this code to your website!

After several hours following the publication of the article, we have received several reports of people unhappy, because they wanted access to the website complete even using their cell phone and the mobile version, so
we were forced to disable this code on our website. 

What have we learned? Two important lessons: 

  • People hate when they get redirected to some "mobile version"and there's no easy way to visit "normal" version.
  • If we really  want to reduce the bandwidth and complexity of the website, the redirect operation needs to be done on the server-side and not javascript.

Apply the proposed code EXCLUSIVELY if you are obliged and have the right reasons. 

---------------------------------------------------------------------------------------------------------------------------------------------------

Thanks for reading and for all the positive comments you have given in recent weeks. If you want to say thanks to me, please visit my latest creation :

http://www.localstreamer.com/friendadder.html 

and retweet it. Search by location: facebook profiles and twitter users to follow.

---------------------------------------------------------------------------------------------------------------------------------------------------

| Viewed
times | Favorited 0 times
Filed under:                  

76 Comments

Apr 16, 2011
Mike Scott said...
I'm not going to be using your website, clearly, as this code is terrible. First, it needs an option for a user on a mobile device to say that they want the real website, not the mobile one, and not get redirected. Second, if a mobile user follows a link to a page on your website, you're then going to redirect them to the mobile homepage, rather than the mobile version of the page that they want.
Apr 16, 2011
Thomas said...
That's the fastest way to guarantee I'll never visit your site. There's no excuse for using mobile view on a smartphone and especially not when you force it on users!
Apr 16, 2011
verascienza said...
Hello i am one of the developer here, Thanks to all for the feedback, we make a note of your suggestions and will disable soon the redirect to mobile website.
May 04, 2011
Mike said...
The javascript code worked perfectly for me. I tested with Firefox, Internet Explorer and Chrome and I was not redirected. I tested with several Androids, an iPhone and an iPad and I was redirected to my mobile page. I added a link on my mobile page to go to the main page if I get a false positive. I also added a link to my main page that goes to the mobile page in case some I do not detect a particular mobile device. Good work.
May 05, 2011
Tom said...
Worked great for me. I have a client with a full flash site site that is useless to iphone users and others. By auto-directing them from the main page to basic mobile ready pages with simple jpgs, it saves us from the user experiencing a blank page representing the company. This was quick to install, while the server side solutions appeared to be hours to implement; overkill. Thanks for the code!
May 09, 2011
Joey said...
for mobile users, you can redirect them to a page which has an option to view the non-mobile page. it's easy! so what's with those first two comments (mike and thomas). be a little more creative with your work.
May 09, 2011
Joey said...
for mobile users, you can redirect them to a page which has an option to view the non-mobile page. it's easy! so what's with those first two comments (mike and thomas). be a little more creative with your work.
May 10, 2011
Adam said...
Worked perfectly for me after trying a few redirect codes that didn't. You rock! Until I get the time to build a mobile site, I'll be redirecting my clients to my old "good enough" website.

Thanks
-Adam

May 15, 2011
Melissa said...
I second Mike's comment from May 4th. I did the exact same thing ... links on each site to the other. It seemed like common sense to me. Your code works perfectly. I am using it and will continue to. There are several reasons to force mobile users to a mobile site ... like flash not being supported on some devices, but working very well on the regular site. Image size is another good reason for sending mobile users to a mobile site. There are more reasons, but I'm sure my point is clear. In consideration of how mobile devices may render (or not render) a site, it is wise to detect mobile browsers and present the most compatible web site.
May 22, 2011
Patrycja said...
you have a really well designed website. nice
Jun 06, 2011
Bryce said...
Is there a certain version of javascript that this code snippet requires? And is there anything else that I need to add before this code? Thank you
Jun 06, 2011
verascienza said...
This snippet uses regular expression, JavaScript 1.2 and later has built-in support for regular expressions. So this snippet works from Internet Explorer 4 and later, all versions of Firefox, and most other modern web browsers support JavaScript 1.2. JavaScript's regular expression flavor is part of the ECMA-262 standard for the language. So @Bryce this will work on all browsers.
Jun 07, 2011
Thea said...
Thank you so much for this code, i searched for a code like this since many hours and finaly i found it and it works :) thank you!
Jun 07, 2011
verascienza said...
Thanks for all the positive comments you have given in recent weeks. If you want to say thanks to me, please visit my latest creation http://www.localstreamer.com/friendadder.html and retweet it: thank you all!
Jun 21, 2011
Bryce said...
When i put a link back to my desktop(non-mobile) homepage it does not work, is there anything else special i would have to do?
Jun 21, 2011
Richard said...
This code works to redirect me. But if i just put a link to go back to the non mobile page it catches it and goes back to the mobile page. How would i get around that?
Jun 22, 2011
verascienza said...
@Richard if your page is cached, try to append a random parameter to the link so for the browser it will be a new page. For example if your to non mobile is href="../index.html" make it href="../index.html?r=654234" . Remember to genereate the random code everytime the page is called.
Jun 27, 2011
Carson said...
Thanks for this, I used it to detect mobile, then alter a link to a video file on it (from a flash, to an MP4 file).
Jun 30, 2011
Hello. can someone give me some creative solutions?
I wish to use the Javascript on www.norse-solutions.com so the vistors wil be redirected too an folder named "www.norse-solutions.com/mobile". This is easy with the script - thank you!
BUT i will have an link-opption on the mobile site on top that offer the viewer to see the main site that is "www.norse-solutions.com " if they want that. The problem is as some of you get right away, thei will then be redirected back to my "mobile" folder. I then have created an LOOP - so i can`t do it like that.

Is there any that have some ideea? I cant have two simelar index files reg. Google Optimations - so what do i do??

Help :)

Jul 07, 2011
Tenley said...
Worked like a charm. Thanks!
Jul 21, 2011
Thank you for sharing this code.
It works pefrectly.
I need this as the main website to an age to load on a mobile phone, the redirect now loads the mobile version in a fraction of the time!

Priceyboy

Jul 21, 2011
Alyssa said...
It works great, we have a mobile version for our flash-based site. But we have found that since our original site is Flash, google is liking our mobile version a whole lot more, and computer users are being directed to pages on our mobile version, which don't look nearly so pretty on a desktop browser. Is there a reverse code that I can put into the mobile site that will detect browsers that AREN'T mobile based and direct users to our regular website?

Thanks in advance!

Alyssa

Jul 21, 2011
verascienza said...
@Alyssa to do an action for not mobile users simple take the same code and use the 'not' operator in the 'if' ... so the code is

if (!mobile) {
document.location = "http://www.mynotmobilewebsite.com";
}

Jul 21, 2011
Alyssa said...
@EyeQ Webdesign Norge - I'm guessing you only have the code on the index page of your regular site, so a simple workaround to avoid an infinite loop would be to create a duplicate of your index page that doesn't have the code, and have the mobile link back to the mainsite go there. That way they can still reach all the other areas of the site that way. Of course, there will still be an issue if they hit "home", as it will once again return them to the mobile version, where they will then have to hit the link to the mainsite again. But if they are that desperate to see your mainsite instead of you mobile version, I'm sure they will figure it out.

And to the people suggesting that there is no reason to redirect people to a mobile version - one word: Flash. Yes, it may be horribly flawed, and not supported in many browsers, and hated by google, and have a million other reasons why it shouldn't be used, but the bottom line is that it still gets used, and I've had many clients specifically request it for it's "ooh, ahh!" appeal. I'm not going to say no to my clients, I will explain the drawbacks, but if they want Flash, I will give them Flash, and I will make it work. This script is one more way to do that.

Jul 25, 2011
Thanks for help!
New questions: I am testing my clients website on a HTC HD2 with Windows Mobile 6.5 - it did not redirect. I have copy/past the code - but on WM 6.5 it did respond. Are there others that have the same problem?
Jul 26, 2011
LhTan said...
after i put the code into dektop index.html it will auto detect and connect to mobile wap.
But how can i from mobile wap view to desktop index.html again...
because it always auto detect the code....
Have any source code to solve the problem?
Jul 26, 2011
LhTan said...
after i put the code into dektop index.html it will auto detect and connect to mobile wap.
But how can i from mobile wap view to desktop index.html again...
because it always auto detect the code....
Have any source code to solve the problem?
Jul 26, 2011
Alyssa said...
Arg! I keep trying to post the code for you, LhTan, but it won't work! I have a javascript snippet you can paste into each page of your mobile version, so if anyone on a regular browser should accidentally happen upon it, it will automatically redirect them to the correct full version of the page. It's a simple code that recognizes the size of the browser window, and if it's over 700px (well over any mobile browser) it sends the user wherever you would prefer them to be. Just swap out the url for the url of the page you want them to be on instead.

[code]

[/code]

Good luck! I hope it works for you - it's working beautifully for me!

Jul 26, 2011
Alyssa said...
Arg! I keep trying to post the code for you, LhTan, but it won't work! I have a javascript snippet you can paste into each page of your mobile version, so if anyone on a regular browser should accidentally happen upon it, it will automatically redirect them to the correct full version of the page. It's a simple code that recognizes the size of the browser window, and if it's over 700px (well over any mobile browser) it sends the user wherever you would prefer them to be. Just swap out the url for the url of the page you want them to be on instead.

Good luck! I hope it works for you - it's working beautifully for me!

Jul 26, 2011
Alyssa said...
it's deleting my code from the message....not sure what I can do? Is there a trick to posting code in this forum?
Jul 26, 2011
LhTan said...
Thank you, Alyssa.
i am intern student. i need the javascript code about if it's over 700px (well over any mobile browser). for my mobile wap project.
can u post to me? loonhong@gmail.com
Thank you very much!
Jul 26, 2011
LhTan said...
Thank you, Alyssa.
i am intern student. i need the javascript code about if it's over 700px (well over any mobile browser). for my mobile wap project.
can u post to me? loonhong@gmail.com
Thank you very much!
Aug 11, 2011
Lytos said...
Funciona perfectamente. Gracias por el script.
Ver prueba en http://www.ks-keepinshape.com
Aug 15, 2011
Jason said...
This is exactly what I am looking for. People! Stop complaining that it doesn't do EVERYTHING for you. I went ahead and had it re-direct to a site where you could chose from there weather or not you would like to use the mobile version, or the flash etc. version. That took me all of 5 minutes? Grow up. Great work, way to keep it nice a simple. THANKS!
Aug 29, 2011
David W Gray said...
I'm new to this redirect code. After hours of research and a few failures, I found your code and it works very well so far. I'm still waiting for results from some real testers. I even added "kindle" to the list and it worked. Thank you!
Sep 14, 2011
Chef Mark said...
This script does exactly what it said it would do. It works perfectly. I have a basic HTML with some js and css page. I simply applied this in the of my index page and created a duplicate index-2 page if a visitor wants to look at the full site instead of the mobile one. Thanks this helped me a ton!
Sep 14, 2011
Chef Mark said...
This script does exactly what it said it would do. It works perfectly. I have a basic HTML with some js and css page. I simply applied this in the of my index page and created a duplicate index-2 page if a visitor wants to look at the full site instead of the mobile one. Thanks this helped me a ton!
Sep 15, 2011
sandy said...
Hey, Thanks for Code. I have used this code on my site its working very fine.
Sep 16, 2011
AJ said...
Good code - helped my project. For those who would be upset because of the mobile vs non-mobile index pages, consider the context of the situation. If I am delivering HD content through a fast wire to a desktop, the non-mobile is fine. If you show up with a smart phone on slow wireless, you will not want to see the HD video, rather, it would make sense to deliver video content custom-tailored to your device. That is why this code makes sense in the context that I use it in. I can detect your device, detect what you can play and what you can't play, and then deliver something you can actually view and enjoy.
Oct 20, 2011
JeffLQuandt said...
Thanks. Great Code, just what I was looking for. Works with my WinMobile 6.5 HTC TP2 just fine. Created a View Full Site link on the mobile page to link to a secondary home page (sans detector) and works just fine. You need to modify the HOME page link on your full site to go back to the secondary home page.
Oct 23, 2011
Jorge Sousa said...
Hi, thanks for the script.
I used it to redirect to a new mobile project, imo.com.pt, and works fine.
The problem are the TABLETS, they need a site type mobile, but diferent.
How can I includ a redirect to a 3º site, exclusive to tablet devices?
Thanks
Oct 25, 2011
Brian said...
Why not a little twist to the code? Instead of automatically redirecting them, have a javascript confirm popup saying, "Would you like to visit the mobile version of this site", if OK, then redirect, if cancel, then no?

Something Like this?

Nov 01, 2011
cognostek said...
Hi,
I need a re-direct script exactly for blackberry storm2 9550 model. Can any 1 help me on this..
Nov 29, 2011
Paulo said...
"verascienza said...
@Richard if your page is cached, try to append a random parameter to the link so for the browser it will be a new page. For example if your to non mobile is href="../index.html" make it href="../index.html?r=654234" . Remember to genereate the random code everytime the page is called. "

Ok, but, please, how to do this?

Nov 29, 2011
jean-pierre said...
The redirect works fine but I noticed that the "../index.html?r=654243" does not work for me. It keeps looping. Can somebody help me on this?
Thank you
Dec 02, 2011
Gary said...
I would like to know how this script could work for the new Kindle Fire?

I have added kindle and silk to the mobile variable but it doesn't seem to detect it.

Any Suggestions?

Dec 05, 2011
Cody said...
Just used your mobile redirect and it works awesome right out of the box. Thank you big time for sharing. Keep up the good work
Dec 21, 2011
Your code is running on my company's website. Saludos from Valparaíso, Chile.
Dec 28, 2011
Amar said...
Hi,

Does this code work for detecting Nokia, Sony Ericson, LG, Samsung, etc devices? What needs to be added in the code snippet for it to detect these.

Thanks much in advance

Jan 03, 2012
Rob said...
People are complaining that there isn't a choice between mobile and regular. Is it not the coders responsibility to do this? I used this script and tweaked it so that when it detects a mobile device it redirects to a page that asks "Would you like the Mobile Version or Regular Version?" and the user clicks what they want. And if they just go to the site on a computer it doesn't ask them it just goes to the main page. It took all of 1 line of code and I made sure that the mobile version of the site was written so that when links are clicked the user stays on the mobile side instead of being jumped back to the regular. I guess what I'm trying to say is. Quit bitching about what isn't written for you and use this as a stepping stone to write your own code.
Jan 06, 2012
Sujoy Ghosh said...
Thanks, this small code helped me a lot. Thank you (Mr. Code'r).
Jan 16, 2012
Chris said...
I have been searching for ages for a script which allows an image viewer script to run only for desktop or laptop users, as the viewer breaks under ipad, iphone and android. This script is perfect with a modification to fire the viewer.init command instead of a redirect as used here when the user is on desktop or laptop browser.
Thanks.
Jan 22, 2012
David Karlins said...
1 - No need to be defensive about redirecting visitors to a mobile page. You can't please everyone and it is the web designer's job to make some choices.

2 - I want to promote this blog and script in my upcoming book - please contact me asap so I can credit you appropriately. Thanks!

Jan 26, 2012
Manoel said...
This code is nice! My cell is a Nokia. I added her name in the code and then the redirect worked perfectly. Congratulations.
Jan 27, 2012
Darryl said...
Thank You.
Jan 28, 2012
Craig said...
How do I have a link at the bottom of my mobile website going to the full site? I used the script but it keeps going to the mobile website.
Feb 03, 2012
John said...
This is very helpful, thank you.
But is there any way I can hide a java script, for example http://mobilewebsite180.com/DM_redirect.js, if I browse is I can see the scripts on the browser, is there a function that can redirect to http://mobilewebsite180.com/ when some one try to browse http://mobilewebsite180.com/DM_redirect.js

Your help is much appreciated
Thanks in advance

Feb 04, 2012
Xanthi said...
Thanks for the code! I have a client and I just had to redirect some pages viewed from an ipad to a mobile version of the site. Worked like a charm. Thanks so much!
Feb 20, 2012
Christopher Postlethwaite said...
Works great thank you very much for your help
Feb 29, 2012
Jae said...
I love the code, been using it for some time. I am in need of a new code now though. Something that sets a cookie or something so I can direct people to the full site with out cloning the homepage without the code. Anyone have such a thing?
Mar 05, 2012
elsie said...
why does it keep looping and not loading on my regular browser as if it is trying to go to both my mobile site page and my regular page??? (NON-mobile) when I have it redirecting and the optional -index-2.html?
Mar 06, 2012
IT works fairly well! It just doesn't detect windows mobiles. Thanks!
Mar 12, 2012
Robby said...
Don't waste your time, this does NOT work. More online bs.
Mar 12, 2012
Gary said...
And what seems to be the problem Robby? it works fine for me.
Mar 13, 2012
Bill said...
The script worked just as you said. I've been struggling for an html solution to avoid going php. the index.html?r=654243 did not work for me to get to the main page. For now, I'll have a duplicate home page with robot text stopping duplicate content and having mobile users go there to view the entire site. Nice job.
Mar 13, 2012
Rob said...
http://ajaxhistory.com/other-scripts/detect-mobile-device-phone-with-javascript/
is a javascript version of detecting a mobile device. needs some tweaking but using an if statement and a redirect line should work perfectly for those who do not have php servers.

Side note I tweaked the above code and am updating a database to track how many mobile devices are viewing my website while at the same time allowing them an alternative to a mobile friendly version of the site.

This code works perfectly.

Mar 13, 2012
shae said...
Does anyone have a good solution to allow users to still choose the Full Site while still using java?
Mar 17, 2012
quinten said...
thank you! after half an hour of browsing page long scripts and explanations finally a simple working one!
Mar 17, 2012
quinten said...
thank you! after half an hour of browsing page long scripts and explanations finally a simple working one!
Mar 20, 2012
Keshri Nandan said...
But what to do in case PC browsers are masquerading the user-agent as mobile browsers ?
Mar 21, 2012
Rob said...
i would do what ever the code is designed to. If I'm masquerading as a mobile browser then the script will think im using a mobile device and redirect or run the function that the mobile script is written to do.
Apr 04, 2012
Drucilla said...
I just want you to know that your code was helpful for my situation. I develop e-Learning and I needed code that would redirect iPad users to a page that has a play button, since you cannot auto-play videos on iPads. I wanted to keep the page clean (without a play button) for our typical audience that will just see our branded video intro auto-play before beginning a course. We have a transcript (in white code, so sited visitors don't see it but screen-readers will read it) and a skip intro link. The video is just photos, logo and text and plays a low-volume instrumental audio in the background.
Apr 05, 2012
Keith said...
This code works great, but today I discovered that it doesn't work for most of the HTC phones. Maybe this is because they're using internet explorer for their browser? Any ideas on what should be added to this code to reach them as well?
Apr 10, 2012
Sarah Allison said...
Thanks. This works on the iPhone at least. Will be implementing it on my web store to optimize for mobile sales. Thank you very much!
Apr 22, 2012
serbanghita said...
May I suggest not to do this client-side but rather server-side. Check this lightweight script that works (if you don't want to use APIs): http://code.google.com/p/php-mobile-detect/
May 07, 2012
It oklahoma said...
I was just now searching for about this when I discovered your post. I’m just stopping by to say that I really enjoyed reading this post, it’s very well written. Are you planning to write more on this? It seems like there is more depth here for more posts.

Leave a comment...