解决使用window.history.back(),返回上一页后,页面不刷新问题

本文介绍了一段用于浏览器页面的JS代码,该代码可以在页面回退显示时触发自动刷新功能。适用于那些需要确保用户看到最新页面状态的应用场景。

在返回的页面增加以下js代码

window.onpageshow = function(event) {
			if (event.persisted || window.performance &&
                window.performance.navigation.type == 2) {
				window.location.reload();
			}
		}

 

在 B 页面使用 `window.location.href` 跳转后,默认情况下浏览器的历史记录会更新,直接使用 `window.history.back()` 会返回到跳转前的上一个历史记录,而是期望的特定页面。为了实现保留性地执行 `window.history.back()`,可以采用以下几种方案: #### 方案一:使用 HTML5 的 `history.pushState` 和 `history.replaceState` `history.pushState` 和 `history.replaceState` 方法可以在刷新页面的情况下修改浏览器的历史记录。在 B 页面跳转前,使用这两个方法来记录需要返回的状态。 **B 页面代码示例**: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page B</title> </head> <body> <button id="jumpButton">跳转到 C 页面并保留返回 B 页面的能力</button> <script> const jumpButton = document.getElementById('jumpButton'); jumpButton.addEventListener('click', function() { // 使用 pushState 记录当前页面状态 history.pushState({ page: 'B' }, 'Page B', 'b.html'); // 跳转到 C 页面 window.location.href = 'c.html'; }); </script> </body> </html> ``` 在 C 页面,可以直接使用 `window.history.back()` 返回到 B 页面。 #### 方案二:使用 URL 参数传递信息 在 B 页面跳转时,通过 URL 参数传递一个标识,在目标页面根据这个标识来决定返回页面。 **B 页面代码示例**: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page B</title> </head> <body> <button id="jumpButton">跳转到 C 页面并保留返回 B 页面的能力</button> <script> const jumpButton = document.getElementById('jumpButton'); jumpButton.addEventListener('click', function() { // 跳转到 C 页面并传递参数 window.location.href = 'c.html?from=b'; }); </script> </body> </html> ``` **C 页面代码示例**: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page C</title> </head> <body> <button id="backButton">返回 B 页面</button> <script> const backButton = document.getElementById('backButton'); backButton.addEventListener('click', function() { const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('from') === 'b') { window.location.href = 'b.html'; } else { window.history.back(); } }); </script> </body> </html> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值