javascript - Handling Back Button from browser in React - Stack Overflow

After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back

After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back button in the browser.

I`m not using Redux but only React.

After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back button in the browser.

I`m not using Redux but only React.

Share Improve this question asked Aug 7, 2017 at 9:44 Prateek ThapaPrateek Thapa 4,9481 gold badge11 silver badges25 bronze badges 4
  • Possible duplicate of how to stop browser back button using javascript – Liam Commented Aug 7, 2017 at 9:47
  • Why not redirect the user to the Dashboard ponent if the user is already logged in, in the Login ponent? – glhrmv Commented Aug 7, 2017 at 9:50
  • 1 what is expected behaviour when user clicks back button? – Maxim Kuzmin Commented Aug 7, 2017 at 10:03
  • Redirecting it to the same page. – Prateek Thapa Commented Aug 7, 2017 at 10:12
Add a ment  | 

2 Answers 2

Reset to default 4

I think this will help, if the user is logged in then stay on the same page.

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

I prefere using my custom hook to intercept browser's back navigation:

import { useEffect, useRef } from "react";

// Intercepts browser's Navigate Back event
export const useNavigateBack = (callback: Function): void => {
  const isInitialMount = useRef(true);
  
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      
      window.addEventListener('popstate', function(event) {
        window.history.pushState(null, '', document.URL);
        event.stopImmediatePropagation();
        callback();
      }, false);
    } else {
       // In my special case this fix was needeed:
       // window.history.pushState(null, '', document.URL);
    }
  }, [callback]);
}

And now I can call use useNavigateBack([my custom back navigation handler]) inside my ponent.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744168614a4561424.html

相关推荐

  • javascript - Handling Back Button from browser in React - Stack Overflow

    After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信