0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】PerformanceNavigationに格納される情報についてのメモ

Posted at

概要

今回実現したかったこととして、beforeunloadのイベントが起きた際に、それがリロードなのか別サイトに遷移するかの判定を行うというものです。PerformanceNavigationが使えるのではないかと考えましたが、結論から言うとこれは無理っぽいです。一応なぜ実現困難かについてメモ書きを残しておきます。
なお、beforeunloadの動作については【JavaScript】俺の書いた離脱防止用beforeunloadイベントがなんかおかしい件を参照ください。

PerformanceNavigationについて

URLアクセスとページリロードの判定処理についてにて紹介されていますが、PerformanceNavigationで取得できる情報はあくまで「ユーザがそのページにアクセスした手段を取得」です。したがってbeforeunloadが発火した時の操作ではありません。

実験

以下のようにreactでbeforeunloadを実装してみて、PerformanceNavigationの情報を取得してみました。結果としてはあくまでこのページに入ってきた時点の情報であり、beforeunloadで捕捉した状態を取得できるわけではありません。

import { useEffect } from "react";

export default function Home() {
  useEffect(() => {
    const beforeUnloadHandler = (event: BeforeUnloadEvent) => {
      // このnavigationTypeはあくまでこのページに来たときの情報
      const navigationType =
        window?.performance?.getEntriesByType("navigation")[0];
      console.log(navigationType);
      event.preventDefault();
    };

    window.addEventListener("beforeunload", beforeUnloadHandler);
    return () => {
      window.removeEventListener("beforeunload", beforeUnloadHandler);
    };
  }, []);

  return (
    <div>
      <div>test</div>
      <input type="text" id="name" name="name" />
    </div>
  );
}

その他参考

onbeforeunload onunload performance.navigation.type not working properly

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?