あまり使う機会はないかもしれませんが、Macでだけ表示が崩れてCSSを分けたいことがあったので、ユーザーエージェントを取得してMacを判別する方法を調べてみました。
サンプルコード
「Mac」と「OS」を含むユーザーエージェントで判別できるようです。
ただiPhoneやiPadも含まれてしまうので、それらは除外します。
JavaScript
1 2 3 4 5 6 7 8 9 10 | var ua = navigator.userAgent.toLowerCase(); // Mac var isMac = ((ua.indexOf( 'mac' ) > -1) && (ua.indexOf( 'os' ) > -1)) && !((ua.indexOf( 'iphone' ) > -1) || (ua.indexOf( 'ipad' ) > -1) || (ua.indexOf( 'windows' ) > -1)); // 使用例 if (isMac) { alert( 'Mac' ); } |
ua.indexOf(‘windows’) > -1 は「mac」と「os」だと Windowsの何かに引っかかったりがあり得そうな気がしたので入れていますが、なくてもいいかもしれません。
iPhoneなどを含んだMac判別のデモページ
iPhoneなどを含めたい場合は、除外の記述を外せばOKです。
JavaScript
1 2 3 4 5 6 7 8 9 10 | var ua = navigator.userAgent.toLowerCase(); // Mac var isMac = ((ua.indexOf( 'mac' ) > -1) && (ua.indexOf( 'os' ) > -1)) && (ua.indexOf( 'windows' ) == -1); // 使用例 if (isMac) { alert( 'Mac' ); } |
サンプルコード2
navigator.platformでもできるようです。
JavaScript
1 2 3 4 5 6 7 8 9 10 | var pf = navigator.platform.toLowerCase(); // Mac var isMac = (pf.indexOf( 'mac' ) > -1); // 使用例 if (isMac) { alert( 'Mac' ); } |
【参考サイト】
コメントが承認されるまで時間がかかります。