0

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]);
mrgreen
  • 63
  • 5
  • 1
    It's worth mentioning that relying heavily on preventing page reloads or controlling the user's navigation can have implications for the user experience and browser security. It's crucial to strike a balance between achieving your desired functionality and respecting the user's control over their browsing experience. – MR SHR47 May 16 '23 at 06:31
  • maybe you mean the code `history.pushState(param,'title',url)` or user leave page https://stackoverflow.com/questions/147636/best-way-to-detect-when-a-user-leaves-a-web-page – perona chan May 16 '23 at 06:37
  • @peronachan exact same answers ChatGPT and Bing suggested me. But those things didn't work. I tried all of them. Thanks BTW... – mrgreen May 16 '23 at 06:54
  • lol. my chatGPT doesn't throw an error every time I ask one question. I'm not very good at `react js`. but sometimes i need `react router`. that's why i made my own with `vanilla js` – perona chan May 16 '23 at 07:16
  • @MRSHR47 ... But this is my requirement during Exam Time. – mrgreen May 16 '23 at 07:45

2 Answers2

1

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.

MR SHR47
  • 109
  • 5
  • Thank you. Its working somehow! but that "Bounce Effect" you said is not giving the "Good User Experience". – mrgreen May 16 '23 at 07:43
0

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;

Vishal
  • 178
  • 5
  • Thank you for your time. Fact is it didn't work. I am using firefox and at first it takes me to the redirected url and bring me back to previous page in a moment. But if I reload again, then it takes me to the redirected URL and then it works fine. – mrgreen May 16 '23 at 07:05