參考:https://blog.csdn.net/qq_31915745/article/details/88749334
原因 :
- 安卓手機對微信瀏覽器進行緩存是根據(jù)根路由http://baidu.com/a/b的形式來緩存的,即如果微信瀏覽器緩存過www.baidu.com?lang=en 和 www.baidu.com?lang=zh后,reload默認是從緩存中裝載文檔,而不會刷新重新渲染整個頁面。所以這個時候加時間戳就可以避免被瀏覽器判斷為之前緩存過的頁面。
- app里調(diào)用webview,發(fā)現(xiàn)webview里上述方法reload頁面無效。網(wǎng)上查了一遍發(fā)現(xiàn)沒有說這個問題的。固推測webview的緩存原則是判斷 ? 參數(shù)前的路由路徑,所以導致無法刷新。對于開頭的例子,去掉?后的參數(shù),那么url就都是www.baidu.com,所以webview會判斷為同一路徑,不會reload。
暴力解決: 博主用的react hash路由,固直接在hash前加時間戳就可以解決
const { href } = window.location;
const router = href.split('#/')[1];
const newUrl = `/?lang=${index}#/${router}`
完整代碼:
export function performRefresh() {
console.log("執(zhí)行自動刷新...")
if (typeof window === "undefined") return
try {
const currentUrl = window.location.href
const timestamp = Date.now()
const timeParam = `_t=${timestamp}`
// 檢查是否是 hash 路由(包含 #)
if (currentUrl.includes('#')) {
// hash 路由:在 hash 前加時間戳參數(shù)
// 例如: http://example.com/#/pages/home/index
// 變成: http://example.com/?_t=123456#/pages/home/index
const [baseUrl, hash] = currentUrl.split('#')
// 移除可能存在的舊時間戳參數(shù)
const urlWithoutTime = baseUrl.replace(/[?&]_t=\d+/g, '')
// 構建新 URL:在 hash 前加時間戳
const separator = urlWithoutTime.includes('?') ? '&' : '?'
const newUrl = `${urlWithoutTime}${separator}${timeParam}#${hash}`
// 使用 replace 方式刷新(不會在歷史記錄中留下記錄)
window.location.replace(newUrl)
} else {
// 非 hash 路由:在 URL 后加時間戳參數(shù)
// 例如: http://example.com/pages/home/index
// 變成: http://example.com/pages/home/index?_t=123456
const urlWithoutTime = currentUrl.replace(/[?&]_t=\d+/g, '')
const separator = urlWithoutTime.includes('?') ? '&' : '?'
const newUrl = `${urlWithoutTime}${separator}${timeParam}`
// 使用 replace 方式刷新
window.location.replace(newUrl)
}
} catch (error) {
console.error("執(zhí)行刷新時出錯:", error)
// 備選方案:直接設置 href(最兼容的方式)
try {
const currentUrl = window.location.href
const timestamp = Date.now()
if (currentUrl.includes('#')) {
const [baseUrl, hash] = currentUrl.split('#')
const urlWithoutTime = baseUrl.replace(/[?&]_t=\d+/g, '')
const separator = urlWithoutTime.includes('?') ? '&' : '?'
window.location.href = `${urlWithoutTime}${separator}_t=${timestamp}#${hash}`
} else {
const urlWithoutTime = currentUrl.replace(/[?&]_t=\d+/g, '')
const separator = urlWithoutTime.includes('?') ? '&' : '?'
window.location.href = `${urlWithoutTime}${separator}_t=${timestamp}`
}
} catch (e) {
// 最后的備選方案:使用 reload()
console.warn("使用 reload() 作為最后的備選方案")
try {
window.location.reload()
} catch (e2) {
console.error("所有刷新方法都失敗:", e2)
}
}
}
}