PCサイト・スマートフォンサイトの相互切替をlocalstorageで実装する

構築・開発

レスポンシブやRewriteEngineなどを使用していない、
静的な個別スマートフォンサイトを制作した際に、
PC/SPデバイス毎で、相互切り替えを実装します。

例えば、PCサイトのアドレスが、
http://example.com/
SPサイトのアドレスが、/sp/ となっている場合です。
http://example.com/sp/

ページ遷移した時や2回目のアクセスの対応として、
localstorageを使用したフラグ判定をしております。

相互にページがない場合などで、切り替えを行いたくない時は、
スクリプトを読み込みしなければ、ページ遷移することはありません。

スポンサーリンク

PCページへ読み込むスクリプト

<script>
$(document).ready(function(){
    var storage = 'pc';
    
    //Current URL 書き換え(spディレクトリをドメインの後ろに追加)
    var host = $(location).attr('hostname');
    var current_url = $(location).attr('href').replace(new RegExp(host, 'g'), host + '/sp');
    
    try{
        var userAgent = window.navigator.userAgent.toLowerCase();
        if ((navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || (navigator.userAgent.indexOf('Android') > 0 && navigator.userAgent.indexOf('Mobile') > 0)){
            //localStorageデータ取得
            storage = window.localStorage.getItem("deviceMode");
            if(storage == null){
                //スマホからPCページを見たときに、SP版へ遷移設定
                storage = 'sp';
            }
        }
    } catch(e) {}
    
    if (storage == 'sp') {
        window.location.href = current_url;
    }
    
    //SPページへの誘導バナーがある場合、クリックで切り替え遷移
    if($('#sp-link').length > 0){
        $('#sp-link').click(function(){
            try{
                window.localStorage.removeItem("deviceMode");
                window.localStorage.setItem("deviceMode", 'sp');
            } catch(e) {}
            window.location.href = current_url;
        });
    }
});
</script>

スマホページへ読み込むスクリプト

<script>
$(document).ready(function(){
    var storage = 'sp';
    
    //Current URL 書き換え(spディレクトリを削除)
    var current_url = $(location).attr('href').replace(/\/sp\//g, '/');
    
    var userAgent = window.navigator.userAgent.toLowerCase();
    if ((navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || (navigator.userAgent.indexOf('Android') > 0 && navigator.userAgent.indexOf('Mobile') > 0)){
        try{
            //localStorageデータ取得
            storage = window.localStorage.getItem("deviceMode");
        } catch(e) {}
    } else {
        //PCからのアクセス
        storage = 'pc';
    }
    
    if (storage == 'pc') {
        window.location.href = current_url;
    }
    
    //PCへのリンククリックで、切り替え遷移
    $('#pc-link').click(function(){
        try{  
            window.localStorage.removeItem("deviceMode");
            window.localStorage.setItem("deviceMode", 'pc');
        } catch(e) {}
        window.location.href = current_url;
    });
});
</script>

コメント

スポンサーリンク
タイトルとURLをコピーしました