skip to Main Content

In react I tried to redirect user from current page to another page after reload by using onunload & onbeforeunload. but after first reload it shows the url changed and comeback to current page again. and after second reload it goes to redirected page.
These are some code I tried…

Test 001: Just after confirmation / "Leave Page" button clicked, it should redirect. Fact is it goes to the page and redirect to the previous page. >_<

import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

const MyComponent = () => {
  const history = useHistory();

  useEffect(() => {
    const handleBeforeUnload = (event) => {
      // Prevent the default dialog box from showing
      event.preventDefault();
      // Redirect the user to the desired page
      history.push('/redirected-page');
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [history]);

  // Rest of your component code...

  return (
    // JSX for your component...
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>

Test 002: Then I thought it might be the timing issue and I set a timer. Now things goes worse! it doesn’t go there.

useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();

      // Delay the redirection by 100 milliseconds
      setTimeout(() => {
        history.push('/Applicant-profile');
      }, 100);
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [history]);

2

Answers


  1. Try this :

    import React, { useState, useEffect } from 'react';
    import { Redirect } from 'react-router-dom';
    
    const MyComponent = () => {
     const [shouldRedirect, setShouldRedirect] = useState(false);
    
      useEffect(() => {
       const handleBeforeUnload = (event) => {
        // Custom logic to determine if the page is being reloaded
        // You can check for specific conditions or simply set the flag to true 
       unconditionally
      const isReloading = true;
    
      if (isReloading) {
        event.preventDefault();
        setShouldRedirect(true);
       }
     };
    
     window.addEventListener('beforeunload', handleBeforeUnload);
    
     return () => {
       window.removeEventListener('beforeunload', handleBeforeUnload);
     };
    }, []);
    
    if (shouldRedirect) {
     // Replace 'path/to/redirect' with the actual path you want to redirect to
     return <Redirect to="path/to/redirect" />;
    }
    
     // Render your component content here
     return <div>Hello, World!</div>;
    };
    

    export default MyComponent;

    Login or Signup to reply.
  2. The browser "bounce effect" or "double reload" issue, where the page reloads twice after attempting to redirect the user using the beforeunload event, can be challenging to prevent entirely due to browser security measures. However, you can employ certain techniques to minimize its impact.
    One effective approach is to store a flag data to somewhere globally where you can trace that this user reload that page.

    This guy solved this problem in a way

    I have another solution, which is store a flag in localstorage / sessionStorage and later destroy it while redirection success. Here is the code bellow, you can use it in you own way.

    const current_url = window.location.pathname;
    
    // this function will work only when you do reload. 
      window.onbeforeunload = function () {
        localStorage.setItem("page",current_url) // Store the page URL 
      };
    
    // After first redirection and due to bounce effect will come back to current page.
      useEffect(() => {
      
      // if your localstorage have the key "page and the value is the current page...
        if(localStorage.getItem("page") === current_url){
          
          localStorage.removeItem("page"); // also you have to remove the item from localstorage. 
          history.push("/where_you_want_to redirect") // ... then it will redirect you to somewhere you wish.
        }
      },[])

    Still you will face "bounce effect" but after that it will redirect you again due to flag match and this time "bounce effect" won’t work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search