Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Created July 14, 2023 10:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daliborgogic/fbc0ae5455b6afa1673721931324b5c7 to your computer and use it in GitHub Desktop.
Save daliborgogic/fbc0ae5455b6afa1673721931324b5c7 to your computer and use it in GitHub Desktop.
Vue Router Back/forward cache
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