简体   繁体   English

后退按钮导致哈希更改页面陷阱javascript

[英]back button causing hash change page trap javascript

I store my webpage info in the URL hash, including page number. 我将网页信息存储在URL哈希中,包括页码。 In order to ensure the page does not exceed the total pages I added this condition. 为了确保页面不超过总页面数,我添加了此条件。 assuming total pages = 10 假设总页数= 10

//get page value from URL 
function getParams(val){
    return decodeURI(
        (RegExp('[#|&]' + val + '=' + '(.+?)(&|$)').exec(location.hash)||[,''])[1]
      );
   }


var totalPages = 10;

   $(window).on('hashchange',function(){
   if(getParams('page') > totalPages){
      window.location = "#page=1";
   } 
}); 

the problem is that if the page loads from another time where the total pages were more: 问题是,如果该页面是从另一个页面加载的,而该页面的总页面数更多:

www.website.com#page=11

it redirects to page 1, but then if the user navigates back, it goes back to page 11 for an instant then redirects back to page 1 and gets trapped in that cycle, making it impossible for the user to navigate back. 它重定向到页面1,但是如果用户向后导航,它会立即回到页面11,然后重定向回到页面1并陷入该周期,从而使用户无法导航。 is there any way to prevent this problem? 有什么办法可以防止这个问题? thanks for reading. 谢谢阅读。

I've encountered a similar problem before, use window.location.replace(url) instead of window.location = url; 我之前遇到过类似的问题,请使用window.location.replace(url)而不是window.location = url; so that the previous page will not be saved in the session history. 因此上一页将不会保存在会话历史记录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用ajax捕获后退按钮并刷新页面 - How to trap the back button and refresh the page using ajax 如何使用Javascript捕获后退和前进按钮并刷新? - How to trap the back and forward button and refresh using Javascript? 检测URL中的后退按钮/哈希值更改 - Detecting Back Button/Hash Change in URL 用Javascript重新加载哈希更改页面 - Page reload on hash change with Javascript 哈希不适用于返回按钮; 需要javascript来调用URL更改功能 - Hash doesn't work with back button; Need javascript to call function on url change 如何在javascript中捕获浏览器的后退/前进按钮单击事件或哈希更改事件? - How to capture browser's back/forward button click event or hash change event in javascript? Javascript / jQuery仅在浏览器后退/前进按钮单击时检测哈希更改 - Javascript/jQuery detect hash change only on browser back/forward button click 滚动时更改URL哈希并保持后退按钮正常工作 - Change URL hash on scroll and keep back button working 如何确定location.hash是否从后退按钮更改? - How to determine if a location.hash change from back button or otherwise 是否检测到按下后退/前进按钮时没有轮询? (哈希变化) - Detecting when the back/forward button is pressed without polling? (hash change)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM