PCでスマートフォンサイトにアクセスしたら、PCサイトに切り替え、スマートフォンでPCサイトにアクセスしたら、スマートフォンサイトに切り替える。
基本は、
PC版に以下を組み込み
1 2 3 4 5 6 | ( function (){ var ua = navigator.userAgent.toUpperCase(); if (ua.indexOf( 'IPHONE' ) != -1 || (ua.indexOf( 'ANDROID' ) != -1 && ua.indexOf( 'MOBILE' ) != -1)){ location.href = '/sp/' ; } }()); |
スマートフォン版に
1 2 3 4 5 6 | ( function (){ var ua = navigator.userAgent.toUpperCase(); if (!(ua.indexOf( 'IPHONE' ) != -1 || (ua.indexOf( 'ANDROID' ) != -1 && ua.indexOf( 'MOBILE' ) != -1)){ location.href = '/' ; } }()); |
を組み込めばよいが、それぞれ異なるScriptを読み込ませなければいけないので、管理が面倒。そこで、Scriptを共通化して、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ( function (){ var ua = navigator.userAgent.toUpperCase(); var url = document.location.pathname; var spDir = '/sp/' ; /* 遷移させたいディレクトリ */ (ua.indexOf( 'IPHONE' ) != -1 || (ua.indexOf( 'ANDROID' ) != -1 && ua.indexOf( 'MOBILE' ) != -1))? isSP() : isPC(); function isSP(){ if (url.match(spDir)){ return false ; } else { location.href = spDir; } } function isPC(){ if (!url.match(spDir)){ return false ; } else { location.href = '/' ; } } }()); |
上記のソースコードをuserAgent.jsで保存して、外部ファイルとして読み込む
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < title >PCサイトとスマホサイトの振り分け</ title > < script type = "text/javascript" src = "userAgent.js" ></ script > </ head > < body > ・・・・・ </ body > </ html > |