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?

vue-routerで直接アクセスを判定する方法

Posted at

目的

システム内で直接アクセスやブックマークからアクセスされたくないページがあり、その制御のための判定を作成しました。

実装

router/index.js
let isFirst = true;

router.beforeEach((to, from, next) => {

    const beforePage = sessionStorage.getItem('currentPage')
    const nextPage = to.name;
    const isDirectAccess = isFirst && beforePage !== nextPage

    isFirst = false;
    sessionStorage.setItem('currentPage', to.name)

    next()
})
状況 isFirst beforePage != nextPage isDirectAccess
直接アクセス(ブックマーク)(違うページ) TRUE TRUE
直接アクセス(ブックマーク)(同じページ) TRUE FALSE ×
ページの更新 TRUE FALSE ×
通常のページ遷移 FALSE TRUE ×

解説

  • isFirstは初回のページアクセス時にtrueとなり、その後はfalseに設定されます。
  • sessionStorageを使用して、画面が遷移したかどうかを判定しています。
    • sessionStorageはブラウザのタブごとにデータが管理されるため、異なるタブで直接アクセスした場合はcurrentPageがundefinedとなります。
  • アドレスバーで何も変更せずにEnterを押した場合や、ページ更新をした場合も考慮しています。

注意点

sessionStorageはブラウザのプライベートモードでは使えないので、この点が要件に合わない場合は別の方法が必要ですね。

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?