Monday, March 31, 2014

Web page redirection for mobile devices by checking viewport only

I am facing one scenario where main browser site need to be shown in large devices but for small devices show mobile site.
To do this device profile checking is not enough for me, so need to go with window width.

//under width of 768 mobile site will open.
 if (window.screen.width < 768) {
   window.location = '~/Mobile/Home.aspx'; //for example
 }

//New update : second solution

Now  I extended the functionality, if any desktop page opened in mobile site then that page will be redirected to the mobile version of that page.
NOTE: every desktop page should have their mobile version under "mobile"  folder.

if (window.screen.width < 768)

  var currentPath= location.pathname;
  if(currentPath=='/')
  {
    currentPath="/Home.aspx";
  }
  if((currentPath.indexOf('/mobile/') != -1)||(currentPath.indexOf('/Mobile/') != -1)){
    //console.log("found so no need to redirect");
  }
  else
  {
    //console.log("not found but screen size small so redirect to mobile")
    //console.log('Mobile/'+currentPath);
    window.location = location.protocol +'//'+ location.host+'/Mobile'+currentPath;//Home.aspx
  }
}

No comments:

Post a Comment