中企動(dòng)力網(wǎng)站開發(fā)澎湃新聞
業(yè)務(wù)場(chǎng)景:主項(xiàng)目是用vue寫的單頁面應(yīng)用,但是有多開頁面的需求,現(xiàn)在需要在用戶關(guān)閉了所有的瀏覽器標(biāo)簽頁面后,自動(dòng)退出登錄。
思路:因?yàn)槭遣煌膖ab頁面,我只能用localStorage來通信,新打開一個(gè)標(biāo)簽頁(頁面初次裝載時(shí)),我就往數(shù)組中加一個(gè)頁面,在(頁面關(guān)閉或刷新等)頁面卸載時(shí)移除它。這樣就只需要在頁面裝載時(shí)(load事件)判斷當(dāng)前是不是刷新頁面就可以了,只要是其他來源就直接登出。
2024-01-06 22:23 更新:修改了頁面load事件,在頁面數(shù)組中無頁面時(shí),直接去登錄頁面了,但是還是得把頁面加入到頁面數(shù)組中,那個(gè)return沒有必要。這個(gè)return會(huì)導(dǎo)致進(jìn)入一個(gè)新設(shè)備(或者清空了瀏覽器緩存,即清空了currently_open_page)時(shí),未記錄當(dāng)前頁,那么頁面數(shù)組就是空的,導(dǎo)致打開新頁面時(shí)也直接去登出了。
代碼
import store from '@/store'const cache_key = 'currently_open_page'/*** 主方法,外部只要調(diào)用此方法就可以了*/
export function mount() {window.addEventListener('beforeunload', function () {const currentRoute = getCurrentPage()delPage(currentRoute)})window.addEventListener('load', function () {// 網(wǎng)頁通過“重新加載”按鈕或者location.reload()方法加載if (window.performance.navigation.type != 1) {// 如果頁面不是刷新進(jìn)來,不管是任何來源,都可以認(rèn)為是新進(jìn)入頁面,此時(shí)應(yīng)該就去登錄頁面if (!getCurrentOpenPageList().length) {store.dispatch('user/logout')}// return}// 添加新的頁面const currentRoute = getCurrentPage()addPage(currentRoute)})
}/*** 獲取當(dāng)前的頁面(tab頁面),目前就用時(shí)間值吧* @returns*/
function getCurrentPage() {if (!window._currentPage) {window._currentPage = 'page_' + new Date().getTime()}return window._currentPage
}/*** 獲取當(dāng)前已打開的頁面列表* @returns*/
function getCurrentOpenPageList() {const t = window.localStorage.getItem(cache_key)if (t) {return JSON.parse(t)} else {window.localStorage.setItem(cache_key, JSON.stringify([]))return []}
}/*** 往緩存中新增頁面*/
function addPage(page) {const list = getCurrentOpenPageList()list.push(page)window.localStorage.setItem(cache_key, JSON.stringify(list))
}/*** 往緩存中移除頁面*/
function delPage(page) {const list = getCurrentOpenPageList()const findIndex = list.indexOf(page)if (findIndex != -1) {list.splice(findIndex, 1)}window.localStorage.setItem(cache_key, JSON.stringify(list))
}/*** 清除所有的頁面*/
export function clearAllPage() {window.localStorage.setItem(cache_key, JSON.stringify([]))
}