Created
July 14, 2023 10:32
-
-
Save daliborgogic/fbc0ae5455b6afa1673721931324b5c7 to your computer and use it in GitHub Desktop.
Vue Router Back/forward cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createRouter, createWebHistory } from 'vue-router' | |
const routes = [] | |
const router = createRouter({ | |
history: createWebHistory(), | |
routes | |
}) | |
let dbPromise | |
function openDB(name, view, version = 1, autoIncrement = false) { | |
if (!dbPromise) { | |
dbPromise = new Promise((resolve, reject) => { | |
const req = indexedDB.open(name, version) | |
req.onupgradeneeded = () => | |
req.result.createObjectStore(view, { autoIncrement }) | |
req.onerror = () => reject(req.error) | |
req.onsuccess = () => resolve(req.result) | |
}) | |
} | |
return dbPromise | |
} | |
router.beforeEach((to) => { | |
// Open the connection when the page is loaded or restored from bfcache. | |
window.addEventListener('pageshow', (event) => { | |
if (event.persisted) { | |
console.log('This page was restored from the bfcache.') | |
} else { | |
console.log('This page was loaded normally.') | |
} | |
openDB('bfcache', to.name) | |
}) | |
// Close the connection to the database when the user is leaving. | |
window.addEventListener('pagehide', (event) => { | |
if (event.persisted) { | |
console.log('This page *might* be entering the bfcache.') | |
} else { | |
console.log('This page will unload normally and be discarded.') | |
} | |
if (dbPromise) { | |
dbPromise.then((db) => db.close()) | |
dbPromise = null | |
} | |
}) | |
}) | |
export default router |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment