Redirect based on operating system

3.2k views Asked by At

I'm new here and I apologize if this question is basic/stupid. I am not too familiar with coding, so please excuse my ignorance/glaring errors. I have tried to put this together using code snippets found online and luckily I don't have to code too much for this project.

I am trying to automatically redirect users based on operating system and am really struggling making this happen. Here is the code I am trying to use...assume I know nothing!

<head>
<script type="text/javascript">
<!--
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

if( OSName == "Windows" )
{ 
window.location="http://www.driveweb.com/download-savvy-windows-free/";
}
else if ( OSName == "MacOS" )
{
window.location="http://www.driveweb.com/download-savvy-mac-free/";
}
else if ( OSName == "UNIX" )
{
window.location="http://www.driveweb.com/download-savvy-linux-free/";
}
else if ( OSName == "Linux )
{
window.location="http://www.driveweb.com/download-savvy-linux-free/";
}
else
{
window.location="http://driveweb.com/download-savvy-select/";
}
//-->
</script>
</head>

Thanks again, I sincerely appreciate the help!

3

There are 3 answers

0
Roland Szabo On BEST ANSWER

Use user agent instead, because appVersion is deprecated.

function detectOS(){
   if (navigator.userAgent.indexOf("Win")!=-1) return "Windows";
   if (navigator.userAgent.indexOf("Mac")!=-1) return "MacOS";
   if (navigator.userAgent.indexOf("Linux")!=-1) return "Linux";
   if (navigator.userAgent.indexOf("OpenBSD")!=-1) return "OpenBSD";
   if (navigator.userAgent.indexOf("FreeBSD")!=-1) return "FreeBSD";
   if (navigator.userAgent.indexOf("NetBSD")!=-1) return "NetBSD";
   return undefined;
}
1
Samuel Cook On

this looks correct, although you have a syntax error where you are missing the closing quote on Linux

else if ( OSName == "Linux" )

0
jjthomas3rd On

Aside from the missing quote you could optimize the code as follows to eliminate the if elseif:

<head>
<script type="text/javascript">
if (navigator.appVersion.indexOf("Win")!=-1) window.location="http://mywindowsbased.url";
if (navigator.appVersion.indexOf("Mac")!=-1) window.location="http://myMACbased.url";
if (navigator.appVersion.indexOf("X11")!=-1) window.location="http://mX11based.url";
if (navigator.appVersion.indexOf("Linux")!=-1) window.location="http://mLinuxbased.url";
</script>
</head>

Other than that, not bad for not knowing coding to well.