skip to Main Content

I want a simple redirect to a location when a user clicks the "Back Button" in the Browser.

The problem is, I only want this when he is leaving the page to a different site where he comes from. So find out bounces from the site to redirect them.

That was my try: But it didn’t work :

function bounce_redirect() {
   if ('' === window.top.location.hash && '#' !== window.location.href.slice(-1)) {
       location.replace('/faq');
   }
}

window.addEventListener("popstate", bounce_redirect);

Does someone have an idea how to get that run? It is a school project and not for a live running page as I know, that is not a good way to hold people.

2

Answers


  1. Redirecting a user to a different page when they press the back button can be achieved using JavaScript. However, it’s important to note that this behavior is often considered intrusive and can be disruptive to the user’s browsing experience. Users typically expect the back button to navigate within their browsing history, and forcing a redirect can be frustrating.

     <script>
        // Add an event listener to the window object for the 'beforeunload' event
        window.addEventListener('beforeunload', function (e) {
            // Cancel the default behavior (showing a confirmation dialog)
            e.preventDefault();
            // Redirect the user to the desired page
            window.location.href = 'https://example.com/redirect-page';
        });
    </script>
    

    Please be aware that many users find forced redirects like this frustrating and it can create a poor user experience. It’s generally recommended to use this sparingly and only for specific, well-justified cases, such as when you have a legitimate need to prevent users from going back to a certain page (e.g., to protect data entry or ensure a specific workflow).

    Login or Signup to reply.
  2. as you mention that is not a good way to hold people. and I think isn’t any way to do that without any bugs. i mean without ditching way,
    but I think you can do it by "addEventListener beforeunload"

    and check " window.location.href " is contains what you want or not
    if it isn’t change it to your URL

    something like :

        window.addEventListener("beforeunload", function(event) {
            //  URL before the redirect
     if (!window.location.href .includes(" Your URLS ")) {
    //change it 
     }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search