最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop browser back button using react js hooks and history api? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to disable back button after successful login into the application but couldn't make it. I'm using react router dom 5.2.0 for routing. Currently, I'm redirecting to login page if someone clicks to browser back button but I need to block the back button.

useEffect(() => {
  return () => {
    if (history.action === "POP") {
      history.replace('/login');
    }
  };   
}, [history]);

I'm trying to disable back button after successful login into the application but couldn't make it. I'm using react router dom 5.2.0 for routing. Currently, I'm redirecting to login page if someone clicks to browser back button but I need to block the back button.

useEffect(() => {
  return () => {
    if (history.action === "POP") {
      history.replace('/login');
    }
  };   
}, [history]);
Share Improve this question edited Nov 7, 2021 at 19:02 Ahmet Emre Kilinc 6,98319 gold badges36 silver badges47 bronze badges asked Mar 12, 2021 at 8:06 Avijeet DeyAvijeet Dey 311 gold badge1 silver badge2 bronze badges 1
  • Did you check out my answer? Consider giving some feedback, greetings! – axtck Commented Mar 16, 2021 at 16:24
Add a ment  | 

3 Answers 3

Reset to default 1

Here is how you can stop the browser's back button

  history.pushState(null, null, location.href);
   window.onpopstate = function(event) {
    history.go(1);
  };

There is no way to fully disable the browsers back button, you can only prevent it from going back like you are doing.

When you are doing this, don't forget to listen for events on history, try this out:

useEffect(() => {
  return history.listen(() => { // listen
    if (history.action === "POP") {
      history.replace("/login");
    }
  });
}, [history]);

This code works fine for me :

useEffect(() => {
    return () => {
        if (history.action === 'POP') {
            history.go(1);
        }
    };
}, [history]);
发布评论

评论列表(0)

  1. 暂无评论