参考:https://blog.csdn.net/qq_31915745/article/details/88749334
原因 :
- 安卓手机对微信浏览器进行缓存是根据根路由http://baidu.com/a/b的形式来缓存的,即如果微信浏览器缓存过www.baidu.com?lang=en 和 www.baidu.com?lang=zh后,reload默认是从缓存中装载文档,而不会刷新重新渲染整个页面。所以这个时候加时间戳就可以避免被浏览器判断为之前缓存过的页面。
- app里调用webview,发现webview里上述方法reload页面无效。网上查了一遍发现没有说这个问题的。固推测webview的缓存原则是判断 ? 参数前的路由路径,所以导致无法刷新。对于开头的例子,去掉?后的参数,那么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("执行自动刷新...")
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 前加时间戳参数
// 例如: http://example.com/#/pages/home/index
// 变成: http://example.com/?_t=123456#/pages/home/index
const [baseUrl, hash] = currentUrl.split('#')
// 移除可能存在的旧时间戳参数
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 后加时间戳参数
// 例如: 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("执行刷新时出错:", 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)
}
}
}
}