PageRenderTime 52ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/redirection_mobile.js

https://github.com/Miroan/JS-Redirection-Mobile-Site
JavaScript | 205 lines | 68 code | 36 blank | 101 comment | 20 complexity | 705ea2c789f71834c1a12faac021b518 MD5 | raw file
  1. /*!
  2. * JS Redirection Mobile
  3. *
  4. * Developed by
  5. * Sebastiano Armeli-Battana (@sebarmeli) - http://www.sebastianoarmelibattana.com
  6. * Dual licensed under the MIT or GPL Version 3 licenses.
  7. */
  8. /*
  9. Copyright (c) 2011 Sebastiano Armeli-Battana (http://www.sebastianoarmelibattana.com)
  10. This program is free software: you can redistribute it and/or modify
  11. it under the terms of the GNU General Public License as published by
  12. the Free Software Foundation, either version 3 of the License, or
  13. (at your option) any later version.
  14. This program is distributed in the hope that it will be useful,
  15. but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. GNU General Public License for more details.
  18. You should have received a copy of the GNU General Public License
  19. along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. /*
  22. * This script will cover a basic scenario of full JS mobile redirection.
  23. * The user will be redirected to the mobile version of the site (home page)
  24. * if it's trying to access the site from a mobile device. This check is
  25. * mainly done checking the User-Agent string.
  26. * The mobile URL will be obtained appending a prefix (default is "m") to
  27. * the hostname of the current URL. It's used a naked domain to avoid conflict with
  28. * www.
  29. *
  30. * In some cases the user needs to be redirected to the Desktop version of the site
  31. * from a mobile device. This happens when the user clicks on a link such as "Go to full site"
  32. * or when there is a specific parameter in the querystring.
  33. *
  34. * In that case a new key/value in sessionStorage (for modern browsers)
  35. * will be set and until the user doesn't close browser window or tab it will access
  36. * to the desktop version from a mobile device. There is a fallback for old browsers that
  37. * don't support sessionStorage, and it will use a cookie. The cookie will expiry in one hour
  38. * (default value) or you configure the expiry time.
  39. *
  40. * To use this function, you need to call it as SA.redirection_mobile(config);
  41. * E.g. SA.redirection_mobile ({redirection_paramName : "modile_redirect", mobile_prefix : "mobile", cookie_hours : "2" })
  42. * or
  43. * E.g. SA.redirection_mobile ({mobile_url : "mobile.whatever.com/example", mobile_sheme : "https" })
  44. * or
  45. * E.g. SA.redirection_mobile ({mobile_prefix : "mobile", mobile_scheme : "https"})
  46. * or
  47. * E.g. SA.redirection_mobile ({mobile_prefix : "mobile", mobile_scheme : "https", redirection_paramName : "modile_redirect"})
  48. * or
  49. * E.g. SA.redirection_mobile ({mobile_url : "mobile.whatever.com/example", tablet_redirection : "true"})
  50. * or
  51. * E.g. SA.redirection_mobile ({{mobile_url : "mobile.whatever.com/example", beforeredirection_callback : (function(){alert('2')}) }})
  52. *
  53. *
  54. * @link http://github.com/sebarmeli/JS-Redirection-Mobile-Site/
  55. * @author Sebastiano Armeli-Battana
  56. * @version 0.8.6
  57. * @date 02/04/2011
  58. *
  59. */
  60. /*globals window,document, navigator, SA */
  61. if (!window.SA) {window.SA = {};}
  62. /*
  63. * @param configuration object containing three properties:
  64. * - mobile_prefix : prefix appended to the hostname (such as "m" to redirect to "m.domain.com")
  65. * - mobile_url : mobile url to use for the redirection (such as "whatever.com" to redirect to "whatever.com" )
  66. * - mobile_scheme : url scheme (http/https) of the mobile site domain
  67. * - cookie_hours : number of hours the cookie needs to exist after redirection to desktop site
  68. * - redirection_paramName : parameter to pass in the querystring of the URL to avoid the redirection (the value must be equal to "false").
  69. * It's also the name of the item in the localStorage (or cookie name) to avoid mobile
  70. * redirection. Default value is "mobile_redirect". Eg: http://domain.com?mobile_redirect=false
  71. * - tablet_redirection : boolean value that enables/disables(default) the redirection for tablet such as iPad, Samsung Galaxy Tab, Kindle or Motorola Xoom. - Default:false
  72. * - beforeredirection_callback : callback launched before the redirection happens
  73. */
  74. SA.redirection_mobile = function(configuration) {
  75. // Helper function for adding time to the current date
  76. var addTimeToDate = function(msec) {
  77. // Get the current date
  78. var exdate = new Date();
  79. // Add time to the date
  80. exdate.setTime(exdate.getTime() + msec);
  81. //Return the new Date
  82. return exdate;
  83. };
  84. // Helper function for getting a value from a parameter in the querystring
  85. var getQueryValue = function(param) {
  86. if (!param) {
  87. return;
  88. }
  89. var querystring = document.location.search,
  90. queryStringArray = querystring && querystring.substring(1).split("&"),
  91. i = 0,
  92. length = queryStringArray.length;
  93. for (; i < length; i++) {
  94. var token = queryStringArray[i],
  95. firstPart = token && token.substring(0, token.indexOf("="));
  96. if (firstPart === param ) {
  97. return token.substring(token.indexOf("=") + 1, token.length);
  98. }
  99. }
  100. };
  101. // Retrieve the User Agent of the browser
  102. var agent = navigator.userAgent.toLowerCase(),
  103. // Constants
  104. FALSE = "false",
  105. TRUE = "true",
  106. // configuration object
  107. config = configuration || {},
  108. // parameter to pass in the URL to avoid the redirection
  109. redirection_param = config.redirection_paramName || "mobile_redirect",
  110. // prefix appended to the hostname
  111. mobile_prefix = config.mobile_prefix || "m",
  112. // new url for the mobile site domain
  113. mobile_url = config.mobile_url,
  114. // protocol for the mobile site domain
  115. mobile_protocol = config.mobile_scheme ?
  116. config.mobile_scheme + ":" :
  117. document.location.protocol,
  118. // URL host of incoming request
  119. host = document.location.host,
  120. // value for the parameter passed in the URL to avoid the redirection
  121. queryValue = getQueryValue(redirection_param),
  122. // Compose the mobile hostname considering "mobile_url" or "mobile_prefix" + hostname
  123. mobile_host = mobile_url ||
  124. (mobile_prefix + "." +
  125. (!!host.match(/^www\./i) ?
  126. host.substring(4) :
  127. host)),
  128. // Expiry hours for cookie
  129. cookie_hours = config.cookie_hours || 1,
  130. // Check if the UA is a mobile one (iphone, ipod, android, blackberry)
  131. isUAMobile =!!(agent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i));
  132. // Check if the referrer was a mobile page (probably the user clicked "Go to full site") or in the
  133. // querystring there is a parameter to avoid the redirection such as "?mobile_redirect=false"
  134. // (in that case we need to set a variable in the sessionStorage or in the cookie)
  135. if (document.referrer.indexOf(mobile_host) >= 0 || queryValue === FALSE ) {
  136. if (window.sessionStorage) {
  137. window.sessionStorage.setItem(redirection_param, FALSE);
  138. } else {
  139. document.cookie = redirection_param + "=" + FALSE + ";expires="+
  140. addTimeToDate(3600*1000*cookie_hours).toUTCString();
  141. }
  142. }
  143. // Check if the sessionStorage contain the parameter
  144. var isSessionStorage = (window.sessionStorage) ?
  145. (window.sessionStorage.getItem(redirection_param) === FALSE) :
  146. false,
  147. // Check if the Cookie has been set up
  148. isCookieSet = document.cookie ?
  149. (document.cookie.indexOf(redirection_param) >= 0) :
  150. false;
  151. // Check if the device is a Tablet such as iPad, Samsung Tab, Motorola Xoom or Amazon Kindle
  152. if (!!(agent.match(/(iPad|SCH-I800|xoom|kindle)/i))) {
  153. // Check if the redirection needs to happen for iPad
  154. isUAMobile = (config.tablet_redirection === TRUE) ? true : false;
  155. }
  156. // Check that User Agent is mobile, cookie is not set or value in the sessionStorage not present
  157. if (isUAMobile && !(isCookieSet || isSessionStorage)) {
  158. // Callback call
  159. if (config.beforeredirection_callback) {
  160. if (!config.beforeredirection_callback.call(this)) {
  161. return;
  162. }
  163. }
  164. document.location.href = mobile_protocol + "//" + mobile_host;
  165. }
  166. };