LoginSignup
13
16

More than 1 year has passed since last update.

ブラウザバック感知の備忘録

Posted at

はじめに

仕事でブラウザバック時のみ実行される JavaScript コードを作成したので、その際の知見を書き留めておきます。

画面読み込み完了イベントの発火

ブラウザバック時はキャッシュから画面が読み込まれることも相まって、使用するブラウザによって画面読み込み完了イベントの発火の扱いが異なります。
いくつかあるイベントの種類の中でも、「pageshow」はメジャーなブラウザ(Google Chrome, Firefox, Safari, Edge)のいずれにおいてもキャッシュから読み込まれた場合でも発火します。

ブラウザバックかどうかの見極め

ブラウザやキャッシュの状況によって反応が異なるので、併記した方が良い二つの判定方法を記載します。

1. PageTransitionEvent.persisted

PageTransitionEvent.persisted はキャッシュから読まれたかを boolean で返すプロパティです。

window.addEventListener("pageshow", function(event){
    if (event.persisted) {
        // キャッシュから読み込まれた際の挙動
    }
});

といったように使います。

2. PerformanceNavigationTiming.type

PerformanceNavigationTiming.type は文書ナビゲーションがどのように読み込まれたかを示すプロパティであり、「back_forward」がブラウザの履歴から遷移した際の値です。

window.addEventListener("pageshow", function(event){
    var entries = performance.getEntriesByType("navigation");
    entries.forEach(function(entry) {
        if(entry.type == 'back_forward') {
            // ブラウザの履歴から読み込まれた際の処理
        }
    });
});

といったように使います。

非推奨な判定方法

PerformanceNavigationTiming.type 以前に存在し、現在は非推奨となってる判定手法として PerformanceNavigation.type が存在します。
PerformanceNavigation.type は unsigned short のプロパティであり、2 がブラウザの履歴から遷移した際の値です。

var type = window.performance.navigation.type;
var type = performanceNavigation.type;

といった構文で値を取得できます。

PerformanceNavigation.type はブラウザバックへの対応手法を検索すると使用している記事が見つかることもありますが、現在(2022年2月)時点で使用が非推奨となっており、代わりに PerformanceNavigationTiming.type の使用を推奨しています。

13
16
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
13
16