How can I redirect the user to another page if the user reloads the page?
P粉036800074
P粉036800074 2024-01-29 09:28:37
0
2
393

In react, I'm trying to use onunload and onbeforeunload to redirect the user from the current page to another page after reloading. But after the first reload it shows that the url has changed and returns to the current page again. After the second reload, it goes to the redirect page. These are some codes I've tried...

Test 001: After confirming/clicking the "leave page" button, it should redirect. In fact, it goes to that page and redirects 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 a timing issue and I set a timer. Now things get worse! It won'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]);

P粉036800074
P粉036800074

reply all(2)
P粉926174288

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 ;
}

 // Render your component content here
 return 
Hello, World!
; };

Export the default MyComponent;

P粉938936304

The browser "bounce effect" or "double reload" issue, where a page reloads twice after trying to redirect the user using the beforeunload event, may be difficult to completely prevent due to browser security measures. However, there are certain techniques you can employ to minimize its impact. One effective approach is to store the flag data somewhere globally, where you can track that user reloading the page.

This guy somehow solved this problem

I have another solution which is to store a flag in localstorage/sessionStorage and then destroy it when the redirect is successful. Below is the code, you can use it any way you want.

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.
    }
  },[])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template