Detecting OS version in Javascript and redirecting

烈酒焚心 提交于 2020-01-03 01:59:28

问题


Good Day

I have done some research and found that you can use the following javascript to detect a users OS, whether it is Android, iOS, Windows etc:

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";

document.write('Your OS: '+OSName);

Now what I would like to do is to relocate a user, based on his OS, to either the apple Appstore or google Play Store like this:

HTML:

<a href="" id="redirect">Download our App</a>

and the associated JS

if (OSName="MacOS" ){
$("#redirect").attr("href", "http://www.itunes.com/myapp")
}

elseif (OSName="Linux"){
$("#redirect").attr("href", "http://www.play.google.com/")
}
  (Linux is for Android right? )

Is this the right/best way of doing it/ Will my code work?

Thank you


回答1:


Your code can be simplified:

var playStoreUrl = "http://www.play.google.com/",
    appStoreUrl  = "http://www.itunes.com/myapp",
    platform     = navigator.platform;

if (/mac/i.test(platform))
    $("#redirect").attr("href", appStoreUrl);
else if (/linux/i.test(platform))
    $("#redirect").attr("href", playStoreUrl);
else
    // Handle the case where the OS is neither MacOS nor Linux



回答2:


Yes it'll work.. You can also use this library.

Detect Mobile Browsers JS




回答3:


return {
     isMac105: /Mac OS X 10_5/.test(userAgent),
     isMac106: /Mac OS X 10_6/.test(userAgent),
     isMac107: /Mac OS X 10_7/.test(userAgent),
     isMac108: /Mac OS X 10_8/.test(userAgent),
 };

useragent for mac e.g.

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_1) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25

Macintosh; U; Intel Mac OS X 10_5_8; ru) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5


来源:https://stackoverflow.com/questions/14931598/detecting-os-version-in-javascript-and-redirecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!