ユーザーエージェント文字列を用いた端末識別
JavaScriptでは、navigator.userAgent を解析することで、現在のアクセス元がどのデバイスやブラウザであるかを判定できます。以下は代表的な実装パターンです。
基本的なOS別判別(iOS と Android)
<script>
const userAgent = navigator.userAgent;
const isAndroid = userAgent.includes('Android') || userAgent.includes('Adr');
const isIOS = /\(i[^;]+;( U;)? CPU.+Mac OS X/.test(userAgent);
console.log('Android端末:', isAndroid);
console.log('iOS端末:', isIOS);
</script>
包括的なクライアント環境の検出オブジェクト
複数の端末・ブラウザ・アプリケーション環境を網羅的に判別するための構造化されたアプローチです。
<script>
const clientInfo = {
detect: (function() {
const ua = navigator.userAgent;
const appVersion = navigator.appVersion;
return {
// レンダリングエンジン
isTrident: ua.indexOf('Trident') !== -1,
isPresto: ua.indexOf('Presto') !== -1,
isWebKit: ua.indexOf('AppleWebKit') !== -1,
isGecko: ua.indexOf('Gecko') !== -1 && ua.indexOf('KHTML') === -1,
// 端末タイプ
isMobile: !!ua.match(/AppleWebKit.*Mobile.*/),
isIOS: /\(i[^;]+;( U;)? CPU.+Mac OS X/.test(ua),
isAndroid: ua.indexOf('Android') !== -1 || ua.indexOf('Adr') !== -1,
isiPhone: ua.indexOf('iPhone') !== -1 && !ua.indexOf('iPad') !== -1,
isiPad: ua.indexOf('iPad') !== -1,
// ブラウザ環境
isStandalone: ua.indexOf('Safari') === -1, // PWAやスタンドアロンモード
isWeChat: ua.indexOf('MicroMessenger') !== -1,
isQQBrowser: ua.match(/\sQQ/i) !== null,
// 言語設定
language: (navigator.browserLanguage || navigator.language).toLowerCase()
};
})()
};
</script>
使用例:条件分岐による処理
// モバイル端末かどうかをチェック
if (clientInfo.detect.isMobile || clientInfo.detect.isAndroid || clientInfo.detect.isIOS) {
console.log("モバイル環境です");
}
// WeChat(微信)内かどうか
if (clientInfo.detect.isWeChat) {
alert("微信ブラウザで開かれています");
}
// 現在の言語設定を取得
console.log("使用言語:", clientInfo.detect.language);
簡易リダイレクト:iOS/Android/PCの振り分け
<script>
const ua = navigator.userAgent;
if (/(iPhone|iPad|iPod|iOS)/i.test(ua)) {
window.location.replace("https://example.com/iphone.html");
} else if (/Android/i.test(ua)) {
window.location.replace("https://example.com/android.html");
} else {
window.location.replace("https://example.com/pc.html");
}
</script>
モバイル経由のアクセスかを配列で判定
キーワードリストを使って柔軟にデバイスを検出します。リファラ情報も組み合わせることで、遷移元が空の場合のみリダイレクトする制御が可能です。
<script>
const uaLower = navigator.userAgent.toLowerCase();
const mobileKeywords = [
'android',
'iphone',
'symbianos',
'windows phone',
'ipad',
'ipod'
];
const referrer = document.referrer;
for (let i = 0; i < mobileKeywords.length; i++) {
if (uaLower.includes(mobileKeywords[i]) && (!referrer || referrer === '')) {
window.location.href = 'https://m.example.com/';
break;
}
}
</script>