SHIGANAKUNAI

しがなくないデザイナーを目指す備忘録

JavaScriptでスマートフォンでアクセス時にリダイレクト

久しぶりに使う機会があったのでメモ。jQuery非依存。
ちょっと書き換えればリダイレクト以外にも使えます。全て実機で試したわけじゃないので間違いがあるかも…

基本形

<script type="text/javascript">
if(
navigator.userAgent.indexOf('ユーザーエージェント') > 0
){
location.replace('リダイレクト先のアドレス')
}
</script>

複数の端末にまとめて指定

それぞれの間を『||』で区切ります。

<script type="text/javascript">
if(
 navigator.userAgent.indexOf('ユーザーエージェント') > 0 ||
 navigator.userAgent.indexOf('ユーザーエージェント') > 0
 ){
 location.replace('リダイレクト先のアドレス')
 }
</script>

端末毎に指定

<script type="text/javascript">
if(
 navigator.userAgent.indexOf('ユーザーエージェント') > 0
){
 location.replace('リダイレクト先のアドレス')
}
else if(
 navigator.userAgent.indexOf('ユーザーエージェント') > 0
){
 location.replace('リダイレクト先のアドレス')
}
</script>

ユーザーエージェント

「&&」を使うと条件の絞り込みが出来るみたいですね。
Android(タブレットのみ)は実機で試してませんが、UA偽装では動きました。結構使う機会多いと思います。

//iPhone
 navigator.userAgent.indexOf('iPhone') &gt; 0

//iPhone(iOS6のみ)
 navigator.userAgent.indexOf('iPhone') &gt; 0 &amp;&amp; navigator.userAgent.indexOf('OS 6') &gt; 0

//iPod touch
 navigator.userAgent.indexOf('iPod') &gt; 0

//iPad
 navigator.userAgent.indexOf('iPad') &gt; 0

//Android(スマートフォン・タブレット)
 navigator.userAgent.indexOf('Android') &gt; 0

//Android(スマートフォンのみ)
 navigator.userAgent.indexOf('Android') &gt; 0 &amp;&amp; navigator.userAgent.indexOf('Mobile') &gt; 0

//Android(タブレットのみ)
 navigator.userAgent.indexOf('Android') &gt; 0 &amp;&amp; navigator.userAgent.indexOf('Mobile') &lt; 0

//iPhoneとAndroidのスマートフォンのみ
navigator.userAgent.indexOf('iPhone') &gt; 0 || navigator.userAgent.indexOf('Android') &gt; 0 &amp;&amp; navigator.userAgent.indexOf('Mobile') &gt; 0

使用例(iOSとAndroidのスマートフォンのみ)

&lt;script type="text/javascript"&gt;
$(function() {
 var ua = navigator.userAgent;
 if (ua.indexOf('iPhone') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0) {
 {
 location.replace('リダイレクト先のアドレス')
}
 }
});
&lt;/script&gt;

【参考サイト】http://www.openspc2.org/userAgent/

AKIO KAI

からあげと温泉のまち、大分県出身大阪在住8年目。しがなくないデザイナーを目指してWeb、DTP、映像編集、3DCG、VRとかやってます。

著者の最新記事

コメントをお待ちしております

HTMLタグはご利用いただけません。