4
1

More than 1 year has passed since last update.

Reactでブラウザバックを無効化にするシンプルな2つの方法

Posted at

history.pushStateを使う(javascriptネイティブ)

window.history.pushState(null, '', window.location.href);

これをページ読み込み時に実行すると、履歴の1つ前が自分のページになるので無限に戻れなくなる。javascriptの構文なのでReactに限らずどんなフレームワークでも使えます。

navigateのオプションを使う

navigate('/path/to', { replace: true });

戻るボタンを無効化したいページへ遷移するとき、{replace:true}のオプションを与えると戻れなくなる。

おまけ ブラウザバックを押した奴を無慈悲に怒りたいとき

window.addEventListener('popstate', (e) => {
  alert('ブラウザバックを使うんじゃねぇよ!')
  history.go(1);
});
4
1
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
4
1