WEBTODESIGN

【JavaScript】IEでサイトが開かれたときにEdgeやChromeで開くように促す表示が出るようにする

InternetExplolerのサポートが終了したので、IE対応はしない方向になりましたが、IEで開かれてしまってサイトが崩れているのは困りますよね…。

そんな時のために、InternetExplolerでサイトが開かれたときに本来のサイトの内容を表示せずに、EdgeやChrome等で開くように促す文章が出るようにする記述を標準で入れるようにしています。

コピペできるコード

以下のJavaScriptコードを記述します。

///// IE代替表示 /////
let userAgent = window.navigator.userAgent.toUpperCase(); if(!(userAgent.indexOf('MSIE') === -1 && userAgent.indexOf('TRIDENT') === -1)) { document.body.innerHTML = '<style>.ie{display:flex;flex-direction:column;justify-content:center;align-items:center;width:100vw;height:100vh;}.ie-title{font-size:1.5rem;font-weight:bold;}.ie-text{color:#999;}.ie-link{text-decoration:underline;color:blue;}</style><div class="ie"><p class="ie-title">このサイトは、Internet Explorerでの表示に対応していません。</p><p class="ie-text">Microsoft EdgeやGoogle Chrome等、最新のブラウザからご覧ください。</p><p><a class="ie-link" href="microsoft-edge:'+ location.href +'">Microsoft Edgeでこのサイトを開く。</a></p></div>'; }

上記のコードをコピペで問題ありません。

解説

改行して整形すると以下のような感じです。

///// IE代替表示 /////
let userAgent = window.navigator.userAgent.toUpperCase();
if(!(userAgent.indexOf('MSIE') === -1 && userAgent.indexOf('TRIDENT') === -1)) {
    document.body.innerHTML = '<style>.ie{display:flex;flex-direction:column;justify-content:center;align-items:center;width:100vw;height:100vh;}.ie-title{font-size:1.5rem;font-weight:bold;}.ie-text{color:#999;}.ie-link{text-decoration:underline;color:blue;}</style><div class="ie"><p class="ie-title">このサイトは、Internet Explorerでの表示に対応していません。</p><p class="ie-text">Microsoft EdgeやGoogle Chrome等、最新のブラウザからご覧ください。</p><p><a class="ie-link" href="microsoft-edge:'+ location.href +'">Microsoft Edgeでこのサイトを開く。</a></p></div>';
}

userAgentを使った条件分岐でIEかどうかを判定し、IEだった場合は<body>の中身を指定の内容に置き換える記述です。

window.navigator.userAgent.toUpperCase()

window.navigator.userAgentで使用しているブラウザの名前を取得し、toUpperCase()で大文字に変換しています。

HTMLの部分を整形すると以下です。

<style>
    .ie{
        display:flex;
        flex-direction:column;
        justify-content:center;
        align-items:center;
        width:100vw;
        height:100vh;
    }
    .ie-title{
        font-size:1.5rem;
        font-weight:bold;
    }
    .ie-text{
        color:#999;
    }
    .ie-link{
        text-decoration:underline;
        color:blue;
    }
</style>
<div class="ie">
    <p class="ie-title">このサイトは、Internet Explorerでの表示に対応していません。</p>
    <p class="ie-text">Microsoft EdgeやGoogle Chrome等、最新のブラウザからご覧ください。</p>
    <p><a class="ie-link" href="microsoft-edge:'+ location.href +'">Microsoft Edgeでこのサイトを開く。</a></p>
</div>

適宜インラインCSSやHTMLを変更してください。

インライン表記がおすすめ

すぐに読み込まれたほうがいいので、外部スクリプトではなく、bodyの閉じタグの手前に<script>タグでインライン表記するのがおすすめです。