How to redirect your site to a mobile version through JavaScript
02/11/2010 § 159 Comments
SCENARIO :
The user needs to be redirected to the mobile version of the site (home page) if it’s trying to access the site from a mobile device.
SOLUTION:
UPDATE 25/07/2011 : Version 0.9.5 released with support for “tablet_url”, “keep_path” and “keep_query” properties. Ipad and other tablet devices have been excluded from the list of mobile devices by default. You can use “tablet_redirection” and “tablet_url” parameters for tablets.
To solve this problem, the best approach is implementing something server-side, and I find a good approach using the WURFL file to check the capabilities and features of mobile devices. Read here to know more about WURFL.
Sometimes, a server-side solution can become difficult to implement especially if we have a CDN or reverse proxy (sitting in front of our Web Server) caching our pages.
Here JavaScript comes to the rescue and I wrote a script that makes the redirection happen called “redirection_mobile.js“.
You can find the source here on Github.
The first thing to keep in mind is that the function implemented checks the User-Agent string from the Navigator object and from there it decides if the redirection needs to happen.
In some cases the user wants to access to the Desktop version of the site from a mobile device (sometimes the desktop version has more functionality). The script handles this situation as well, it checks if the previous page hit was one from the mobile site (we can suppose the user clicked on a link such “Go to full site“) or if there is a specific parameter in the querystring of the URL. In those cases the redirection won’t occur. To keep the user in the desktop version for the whole session, sessionStorage object has been used, specifically an item will be stored to distinguish if we’re browsing through the desktop site.
There is a fallback for old browsers that don’t support sessionStorage, and a cookie will be used. The cookie that makes the access to the desktop version from a mobile device possible will expiry in one hour or you configure the expiry time.
iPhone, iPad, iPod, Android phones support completely sessionStorage, there are still some versions of Blackberry that using IE don’t and so we still need the “cookie” fallback.
The function accepts an argument which is a configuration object with few properties:
- mobile_prefix : prefix appended to the hostname, such as “m” to redirect to “m.domain.com”. “m” is the default value if the property is not specified.
- mobile_url : mobile url to use for the redirection (without the protocol), such as “whatever.com”/example to redirect to “whatever.com/example”. If “mobile_prefix” is existing as well, “mobile_prefix” will be ignored. Empty string is the default value.
- mobile_scheme : url scheme (http/https) of the mobile site domain, such as “https” to redirect to “https://m.domain.com”. The protocol of the current page is the default value.
- noredirection_param – up to version 0.6 param was used: parameter to pass in the querystring of the URL to avoid the redirection (the value must be equal to “true”). Default value is “noredirection”. Eg: http://domain.com?noredirection=true. It’s also the name of the item in the localStorage (or cookie name) used to avoid mobile redirection. Prior version 0.9.5 this parameter was called “redirection_paramName”, but I renamed it to make the meaning clearer.
- cookie_hours : number of hours the cookie needs to exist after redirection to desktop site. “1″ is the default value.
- tablet_redirection : boolean value that enables/disables(default) the redirection for tablet such as iPad, Samsung Galaxy Tab, Kindle or Motorola Xoom. – Default:false. The value needs to be a string (so wrapped in double or single quotes). If ‘tablet_url’ parameter not specified, the user will be redirected to the same URL as for mobile devices.
- tablet_url : url to use for the redirection in case the user is using a tablet to access the site. Default value is “”
- keep_path : boolean to determine if the destination url needs to keep the path from the original url. Default value is ‘false’
- keep_query : boolean to determine if the destination url needs to keep the querystring from the original url. Default value is ‘false’
- beforeredirection_callback : if specified, callback launched before the redirection happens. If a falsy value is returned from the callback the redirection doesn’t happen.
To use “redirection_mobile” function, you need to load your script in the HTML of the “desktop” pages and call it as SA.redirection_mobile(config). See the code below:
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/js/redirection_mobile.min.js"/>
<script type="text/javascript">
SA.redirection_mobile ({noredirection_param:"noredirection", mobile_prefix : "mobile", cookie_hours : "2" });
</script>
For instance, in this case, accessing from a mobile device to http://www.domain.com, you’ll be redirected to “http://mobile.domain.com“.
Considering the previous code, from version 0.6, if you hit a page such as “http://domain.com/?noredirection=true” the redirection won’t happen. For all the browser session, if sessionStorage is supported by the browser, the redirection won’t occur. If sessionStorage (HTML5) is not supported, a cookie “noredirection=true” will be stored for 2 hours and it will block the redirection to the mobile site.
If sessionStorage (HTML5) is not supported, a cookie named “noredirection” will be stored for 2 hours and it will block the redirection to the mobile site.
The script from version 0.5 allows you to redirect the user to whatever url. Thus if you need to redirect the user to “https://domain2.com/mobile” now you can invoke the function like this:
<script type="text/javascript">
SA.redirection_mobile ({mobile_scheme:"https", mobile_url : "domain2.com/mobile"});
</script>
Alternatively you can use “redirection_mobile_self.js”, that is it’s an anonyimous self-executing function and it uses it uses the default values for the different properties:
- “mobile_prefix” : “m”
- “redirection_paramName” : “mobile_redirect”
- “cookie_hours” : 1
- “mobile_url” : “”
- “mobile_scheme” : protocol of the current page
- “tablet_redirection” : false
- “beforeredirection_callback” : n/a
It doesn’t need any configuration or any invocation, so you just need to drop it on your webserver and call the script from the HTML of the “desktop” pages . See code below:
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="/js/redirection_mobile_self.min.js"/>
in this case, accessing from a mobile device to http://www.domain.com, you’ll be redirected to “http://m.domain.com“.
To redirect to a desktop/standard version of the site from a mobile device, you may need to embed a link in your mobile pages such as
<a href="http://www.domain.com">Go to main site</a>
and the script included in the desktop page will do the rest.
I also created “redirection_mobile_testable.js” that is just a copy from “redirection_mobile.js”, but it’s using few arguments such as “document”, “window”, “navigator” for testing purpose. Test cases have been written, using QUnit, to test this script and they mock “document”, “window” and “navigator” in a rudimentary way.
The scripts have their minified versions (used YUI compressor).
If you want to test the script on different devises within your desktop browser, you can use a plugin for Firefox called User Agent Switcher, that you can download here.
Feel free to fork the project and improve it if necessary.
..and feel free to make a donation from this page
UPDATE 20/12/2010 : Added support for more devices and fixed a critical issue on IE
UPDATE 05/01/2011 : Version 0.5 released with support for “mobile_url” and “mobile_scheme” properties
UPDATE 02/04/2011 : Version 0.8 released with support for “ipad_redirection” and “beforeredirection_callback” properties
You can support me clicking the DONATE button you can find on my site http://www.sebastianoarmelibattana.com/projects/js-redirection
one quick question – is it me or does this not working with the User Agent Switcher Firefox Plugin – have cleared out cookies but it never seems to redirect – am i missing something?
and one other question where is your donation button?
Nice post.
Please i am having a challenge with my site. How do i redirect a user that clicked on a post-link from an external site (e.g http://www.passnownow.com/inblog.php?id=3887#.UT3dLQCtef0.twitter) from it’s mobile phone to redirect him to the same post on my mobile website (e.g http://www.passnownow.com/mobile/inblog.php?id=3887#.UT3dLQCtef0.twitter)
Here’s an article that explains how to accomplish the same type of redirection leveraging php – there’s also a version for Perl/cgi… http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/ Hope this helps!
I’ve been looking for something exactly like this for quite some time, thanks for sharing your work! The compliment does come with one question
My mobile “site” is a 1-page splash and I’m using PHP to echo the query string in the “return to desktop” link. (This refers the user to the page they had initially requested, basically it echoes the keep_path param that I have set to “true” on my desktop version). My question: Is there a built-in way to do this using your script, or is this the best way?
Thanks again,
Brian
Hi Sebastiano:
THanks for your script!!! I have a quick question. I added the script on my site and it was working perfectly. However, all of the sudden it stop working.. Where is what I added to the header:
SA.redirection_mobile ({
mobile_prefix : “m”,
noredirection_param:”noredirection”,
cookie_hours : “1″,
beforeredirection_callback : (function(){return false;})
});
And this is the link to the full site:
http://www.whiddens.com/?noredirection=true”
What can I do to fix the problem. Before I was able to click on the link and go to the full site and click other links and stay in the full site. Now I don’t get redirected to the mobile site.
Hope you can help me,
Thanks
as you said above, for redirecting a website to a mobile version, is it possible to redirect it to a ipad, if so plz get me the code for that..
thanks
shameer ali shaik
Hi sebarmeli,
Thanks for the great script. I am planning to use it in my site. I have one more question is how do i add a domain to it. eg. If i have a domain 511.org. all the sites which uses the same domain to access the session storage or cookie and see if the previous page accessed is from mobile device and then should not redirect back from desktop.
cheers,
Pawan
Hello Sebastiano,
I’m using your js code, its superb and is working fine until few days back when one of my user find it not working on iphone 4.
Don’t know wts the problem causing it not to work .
Thanks
This is awesome. Works wonderfully, but I do have one question. When someone scans a QR code to go to the website, it doesn’t redirect it. The easy solution would be to change the QR code, but we are trying to avoid reprint costs. Any Suggestions? Thanks!
Hi
I am developing portal applications using websphere portal server and i am using custom theme for mobile on my portal. I have used your code in my theme in head.jsp like below:
SA.redirection_mobile ({mobile_scheme:”http”, mobile_url : “localhost:10039/wps/myportal/asdf/testsample1″});
I have placed the .js file in the appropriate location. Is this enough or do i need to add anymore ?
thanks for the redirection code!!!
mobile works great but not tablet…am i doing it wrong??
SA.redirection_mobile ({
mobile_url : “www.mysite.com/mobile/index.html”,
tablet_url : “www.mysite.com/tablet/index.html”,
mobile_prefix : “https”
});
Hi Sebastiano,
I think your redirecting js is very cool…
I have thought about this same user case too and came up with the following solution:
Basically to allow multiple rendering engines being plugged to the same middle/back-end tier concurrently. By detecting the type of device making the request the web server activates the appropriate rendering engine i.e. desktop vs mobile vs others.
More details at http://pragmatikroo.blogspot.com/2011/04/spring-roodynamic-clients-multiple.html.
I believe my novel approach carries substantial savings on deployment stage and in maintenance too.
Hopefully you and your Reader find interesting this approach too.
B. Roograds
jD
Have been using your script and it was working well until iphone 4s showed up. Now it redirects everything but the iphone. Any hints on how I can fix this?
Thanks Sebarmeli for your article.
Could I use your javascipt to redirect another domain for mobile version?
Example:
My website for all browser: http://www.domain.vn and mobile version is: http://mobiledomain.vn;
Please tell me your way for redirecting domain like my example!
great work!! thank’s for sharing
Works fine for me when testing on iPhone, Blackberry, Opera Mini on an Android smartphone but not on the original Android browser
Thanks so much for this! Many sites gave the code for just the redirection to mobile, but not necessarily the “noredirection” for the “view full site” link. This solved everything…got it working quickly too! Thank you!!!
Do your redirection scripts affect SEO recognition of the underlying webpages?
Hi Sebastiano,
I love the script and it works great, my iPhone redircets perfectly. However when I try to access the site from my PC it re-directs to the mobile site as well.
Any thoughts on why this is happening?
Oh, sir, I cannot seem to make it work. It used to work famously, and somehow it has stopped. I see the script file get called when I watch HTTP live headers, but no redirect. The test seems to be happy:
http://www.sdzsafaripark.org/scripts/mobile/redirect/test/index_test.html
But the actual site doesn’t redirect (to m.sdzsafaripark.org):
http://www.sdzsafaripark.org/
Any help would be gratefully appreciated.
Hi Kristin, the redirection works perfectly fine for me on your website, even in my Android browser for which I can’t seem to make mine work…
This is excellent. I am having trouble with noredirection and have posted my question here: http://stackoverflow.com/questions/8480612/noredirection-with-js-mobile-redirection
hay thnx buddy it was relly helpful…
and the redirecting back to desktop site was what i need the most..
thnx a lot
hi dude,
please solve small problem for me .. i used ur script for redirection to mobile .. you can see the site http://knowledgeindia.in ..
but, it is not working .. can u suggest solution ???
i wanna redirect to m.knowledgeindia.in ..
Thanks a lot .
ARRGGGGHHH!! It’s time to go to sleep, this time I forgot ‘MiniMo’. Moreover you can remove ‘psp’ already matched with the pattern for the PlayStation.
Then the final regex is:
iphone|ipod|blackberry|android 0\.5|htc|lg|midp|mmp|mobile|nokia|opera (?:mini|mobi)|fennec|minimo|palm|pocket|sgh|smartphone|symbian|treo mini|playstation|sonyericsson|samsung|palmsource|benq|windows (?:phone|ce)
Oups! I missed to add the \ for the Android pattern!
iphone|ipod|blackberry|android 0\.5|htc|lg|midp|mmp|mobile|nokia|opera (?:mini|mobi)|fennec|palm|pocket|psp|sgh|smartphone|symbian|treo mini|playstation|sonyericsson|samsung|palmsource|benq|windows (?:phone|ce)
Hi Sebastiano,
First I would like to thank you to provide this script free of charge under dual licence MIT/GPL!
While looking at the last version of your script at Github, I have found some small problems:
- In the agent var, you store the User Agent string lowered AND you specify the i operator (case insensitive) in the regex! You should choose only one of them. If your regex contains only lowered patterns and the user agent string is lowered, you don’t have to use the ‘i’ operator. Same comment for the tablet regex.
- Your regex contains ‘android 0.5′, if you want to test for this exact string, you should write ‘android 0\.5′ because the dot char is a special char meaning ‘Match any single character that is not a line break character’. It works the same but it’s more ‘correct’ for the regex engine.
- Your regex contains MobileExplorer, Windows Mobile and IEMobile. You can remove them because your regex already contains ‘mobile’ and this pattern is always matched before the three others.
- Instead to test for ‘Windows Phone’ and ‘Windows CE’, you should test for ‘windows (?:phone|ce)’. This is exactly the same and more efficient for the regex engine.
- You search for Opera Mini but not for Opera Mobile, using ‘opera (?:mini|mobi)’ instead of ‘opera mini’ will match both of them.
- You test for ‘Playstation Portable’ and ‘Nintendo Wii’. The pattern ‘Playstation Portable’ is used only by the PlayStation 2.0, the PlayStation 3 use ‘PLAYSTATION 3′ or ‘PlayStation 3′ in the User Agent string, then with the pattern ‘playstation’ you will match both versions. The Nintendo Wii normaly use Opera browser already matched by the previous comment, just in case you could test for ‘wii’.
- You missed Fennec and “Mini Mozilla” in your regex!
With the previous comments in mind, the following regex should do the same (and a little bit more) in a better way!
isUAMobile =!!(agent.match(/(iphone|ipod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera (?:mini|mobi)|fennec|minimo|palm|pocket|psp|sgh|smartphone|symbian|treo mini|playstation|wii|sonyericsson|samsung|palmsource|benq|windows (?:phone|ce))/));
That’s all for now!
I hope this will help.
Gilles
This is perfect. Thank you!
Installed the script to my site and it worked GREAT! That is… until I upgraded my iPhone 5 to the new OS. Now it wont work on my iPhone.
I think the cookie that detects if you are coming from the mobile site is BRILLIANT!
Instead of detecting which browser they are using to determine if they should go to the mobile site why not do a screen width check instead. It would avoid having to update for each new mobile device and isnt small screen size why you would want to send them to a mobile site anyway? Do something more like: if (screen.width <= 699) { document.location = "mobile.html";
If you ever produce a version that does the same thing, but redirects based on screen width PLEASE let me know. I would even PAY for a script like that!
If you were using media queries to serve pretty much the same site to desktop and mobile but wanted to modify content *slightly* for the mobile version, could this script be used just to set sessionStorage or cookie which could then be accessed to dynamically modify the content without performing any redirection?
Works great, thank you for this!
This is such a great script!!! It just worked for me on the first try. Thanks so much!!!
hi Sebastiano and hi everyone,
so cool of you to provide this script. I wonder would it work to redirect mobile traffic from one subdomain to another subdomain, rather than from the site root (http://domain.com) to a subdomain?
Any help would be really appreciated. Perhaps giving me an idea of the syntax to use? I’m using the _self.js script.
Thx
Hi there,
I would suggest using not the self version and yeah you can redirect from a subdomain to another as long as you put the script in that subdomain.
HI again, I’m sorry to have troubled you with this, after a little investigation on the matter we found out that the server hosting the mobile site no longer accept .html as main index but .php we are solving the problem, we had a welcome screen as index.php prior to dump the mobile site but the redirection is clearly pointing to index.html, now it is not and we had to delete the php file…
thank you anyway for your prompt answer
p.s. any news on the PC redirection side? I mean avoid PC users to see the mobile version but redirect to the desktop version…
Thank you
Hi Sebastiano
Unfortunately your redirection has stopped working for unknown reason, it all happen this early afternoon, I checked the files and everything seems in order, I did download the latest version but it does not redirect anymore, I’m using this syntax:
SA.redirection_mobile ({
mobile_url : “mysite/index.html”,
mobile_prefix : “http”
});
any help?
Thanks
Can you post the URL? Maybe you’ve got another JS error in your page
Hi Sebastiano,
After applying the redirection_mobile_self.js and editing the script to redirect to mobile instead of m, it still redirects all mobile traffic to the m site.
I can create the m subdomain pretty easily, but I was wondering if you know what I am doing wrong inside the javascript for it to be creating this issue?
Thanks!
Hi Brian,
what did you change exactly in the script? and what exactly do you want to achieve?
Hi Sebastiano,
I basically I changed the mobile_prefix = “m” to “mobile”. However, it is still redirecting whoever visits through a mobile browser to “m” sub-domain.
I am using the redirection_mobile_self.js file.
Image: http://snpr.cm/tGhJzj.png
Weird..did you check your cache configurations?
Hi
I have added the redirection script on and added below on body, becuase i could add this in head because of CMS restriction.
SA.redirection_mobile ({
noredirection_param:”noredirection”,
mobile_prefix : “mobile”,
cookie_hours : “2″
});
It works first time, but after 30 mins, when i browse the site on mobile it is not redirecting to mobile website it display desktop version website.
Js used : redirection_mobile.js 0.9.5
Please help
Dhanraj
Not sure how sessionStorage and getting the user back to the desktop version is handled. If your code is called from a common file on every page on the desktop site, I get a seamless experience, but when the mobile version user gets to the mobile site and clicks the “Desktop” Version link, do I just return to that site and add the query string param or do I do some other magic with this sessionStorage thing? I am kind of an HTML5 newbie.
Hi there,
no you don’t need to do anything, you just use my script and put the link to the desktop version into the mobile page.
Hi,
it would be nice, if a “confirm()” would be prompted. So, the user can decide which version he like…
Hi Sebastiano
Thank you for this script! It should prove perfect for the shared hosting site I am working on.
What are your thoughts on redirecting users to the mobile page if javascript is turned off client side?
I would think very few people do this on their desktop
browsers
Thanks
Larry
yeah, it can be a concern, even if nowadays JS is rarely turned off.
Indeed, there are more spsiiothcated solutions (as mentioned in the post) that should definitely be considered for more serious implementations. However, for things like jQuery plugins that need to deactivate themselves or act differently for a mobile browser, the above snippet will typically be sufficient (and probably more portable).
An update of what I have found. The blackberry did not support it because it did not support external javascript files. It only worked when it was inline javascript. The has also held true for me for Firefox mobile.
Hi folks,
I’m wondering how you all deal with google crawling the site?
In particular, I’m worried about this post:
http://googlewebmastercentral.blogspot.com/2011/02/making-websites-mobile-friendly.html
Particularly this quote:
“It is worth repeating that regardless of URL structure, you must correctly detect the User-agent as given by your users and Googlebot-Mobile, and serve both the same content. Don’t forget to keep the default content, the desktop-optimized content, for when an unknown User-agent requests it.”
I don’t see how a javascript redirect can possibly comply with this directive from Google.
It appears that the BlackBerry was not working properly because it was a cfm (coldfusion) file. It also did not work as a php or aspx file. Works fine as an html file…
@Kyle
You might want to look at the user agent for the blackberry and FF mobile, as all this script does is look at the user agent.
See line 159 here: https://github.com/sebarmeli/JS-Redirection-Mobile-Site/blob/master/redirection_mobile.js and add the appropriate regular expression.
Dan
Awesome Javascript! Very Light-weight! I could not get it to work on the blackberry I have at work for testing purposes and also did not work on Firefox mobile. Worked fine on my Android (default browser) and my co-workers iPhone. Any suggestions? Thanks!
Hi,
I was trying to donate to you, but I don’t have a paypal account and the credit card form only has Australian states on it.
Please take a look at that donation form and let me know when it is fixed, because you totally saved my butt and I’d like to give you some beer money.
Dan
Thanks Dan. At the moment PayPal is the only way to make donation for my work.
Cheers,
Hi,
Great script… I was wondering (also being a js newbie), if there was a simple way to have :
- andropid phones go to m.domain.com
- blackberry phones go to b.domain.com
- iphones go to i.domain.com
Cheers,
Paul
Hi Paul,
not at the moment, and commonly mobile sites are hosted on the same subdomain as they keep the same layout. Maybe you may want to tweak it through CSS.
Cheers