12
5

More than 1 year has passed since last update.

リンクの開かれ方(同窓・別窓)を判定したい

Last updated at Posted at 2023-07-06

やりたいこと

ページAからBへの遷移時、同窓で開かれたか、別窓(別タブ)で開かれたかを判定して表示内容(ボタン)を切り替えたい。


バージョン:Vue 3 (あんまり関係ないですが一応)
<script setup> 構文( https://v3.ja.vuejs.org/api/sfc-script-setup.html


遷移元のページにリンクを貼る

pageA.vue
<!-- 同じ窓で開く場合 -->
<a href="URL">ページBへ</a>

<!-- 別窓で開く場合 -->
<a href="URL" target="_blank" rel="noopener noreferrer">ページBへ(別窓)</a>

ボタンのテキストを切り替えたい

pageB.vue
<!-- 同窓 -->
<button id="btn">前のページへ戻る</button>

<!-- 別窓 -->
<button id="btn">このページを閉じる</button>

これで判定しよう

js
// 直前に閲覧していたページのURLを取得
document.referrer

//ブラウザの履歴リストのURLの数を取得
window.history.length

https://developer.mozilla.org/ja/docs/Web/API/Document/referrer
https://developer.mozilla.org/ja/docs/Web/API/History/length

実際のコード

pageB.vue
<template>
    <button id="btn" @click="clickEvent" v-html="btnLabel"></button>
</template>
<script>
const clickEvent = () => {
    if(document.referrer && window.history.length > 1) {
        //同窓
        btnLabel = "前のページへ戻る";
    
        //ブラウザバック
        history.back();
    
    } else {
        //別窓
        btnLabel = "このページを閉じる";
    
        //ウィンドウを有効化して、閉じる
        window.focus();
        window.close();
    }
}

</script>
12
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5