I am trying to get a jQuery script to redirect to a mobile optimized version of my site under certain circumstances. Basically, if the browser is mobile, it will redirect to the mobile, unless in the URL it gets the argument “mobile=0”. I’ve got a way to detect if it’s mobile, and I have a plugin which lets you get arguments from the URL with jQuery (http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/) which works.
The flow I’d like to have is if it’s desktop, set a mobile variable to 0, and not redirect. Then, if it’s mobile, redirect unless the mobile variable is set to 0 by the url.
Right now, it isn’t redirecting if I am on a mobile browser. I have tested that my redirect works on mobile, but after adding the url parameters, it stopped working.
I started coding, but as I am a bit new at javascript, I know I am making some mistakes. My code so far is:
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad|android|iemobile|ppc|smartphone|blackberry|webos|)/);
var mobile = $.getURLParam("mobile");
if (!agentID) {
mobile = "0";
}
else {
return false;
}
if ($.getURLParam("mobile")==0) {
return false;
}
else {
if (agentID) {
window.location.replace("http://remiwebo.vacau.com");
}
else {
return false;
}
}
Thanks in advance!
I think you’re logic might be a bit more complex than it needs to be.
1) if it’s a mobile – Redirect.
2) if it has mobile=0 do NOT redirect.
3) if it’s a PC do NOT redirect.
What about testing a mobile version on your computer? (mobile = 1)?
update: agentID will = “, “, a 2 character string if it doesn’t find anything in the deviceAgent string. So rather than testing if it’s null, you can check the length of it.
http://jsfiddle.net/3zv64/