user2509333
user2509333

Reputation: 199

Browsers back button click with confirm box

Need to create the javascript confirm pop up on click of browsers back button. If I click on back button pop up will come up and say "you want to go ahead ?" if click on Yes then it would have redirected to previous page.

I have following code it is not working as per the requirement.

if(window.history && history.pushState){ // check for history api support
        window.addEventListener('load', function(){

            // create history states
            history.pushState(-1, null); // back state
            history.pushState(0, null); // main state
            history.pushState(1, null); // forward state
            history.go(-1); // start in main state

            this.addEventListener('popstate', function(event, state){
                // check history state and fire custom events
                if(state = event.state){

                    event = document.createEvent('Event');
                    event.initEvent(state > 0 ? 'next' : 'previous', true, true);
                    this.dispatchEvent(event);

                    var r = confirm("Would you like to save this draft?");
                    if(r==true) { 
                        // Do nothing      

                    } else {  
                       self.location = document.referrer;    
                    }
                    // reset state
                    history.go(-state);

                }
            }, false);
        }, false);
    }

Any help in this would be really appreciable.

Upvotes: 5

Views: 41886

Answers (8)

Sahil Aggarwal
Sahil Aggarwal

Reputation: 61

The solution provided by chri3g91 was the best among the above solutions for me but it had an issue when I tested the solution in my NextJS project that the back button was permanently disabled as I was not able to go back even when clicking on OK button as it then again created a new confirm.

I did some change in the solution and it is now working perfectly fine!

import React, { useEffect } from "react"

function confirmBack() {
    if (confirm('Your current game progress will be lost!')) {
        window.removeEventListener('popstate', confirmBack);
        window.history.back()
    } else window.history.pushState(null, document.title, location.href) // preventing back for next click
}

export default function Component() {
    useEffect(() => {
        window.history.pushState(null, document.title, location.href); // preventing back initially
        window.addEventListener('popstate', confirmBack);
        return () => { window.removeEventListener('popstate', confirmBack) };
    }, [])

    return <>
        {/* JSX Content */}
    </>
}

Upvotes: 1

Monika Nafdey
Monika Nafdey

Reputation: 41

This works for all scenarios, when

  1. user click on back button and cancel the confirmation.
  2. user clicks again on back button and cancel the confirmation.
  3. user clicks again on back button and click ok.
  4. so on...
public componentDidMount(): void {
    history.pushState(null, 'PageName', window.location.href)
    window.onpopstate = (e: PopStateEvent) => {
        if (confirm('Are you sure you want to leave?')) {
            window.onpopstate = (e) => {
                history.back()
            }
            
            history.back()
        } else {
            history.pushState(null, 'PageName', window.location.href)
        }
    }
}
       
public componentWillUnmount(): void {
    window.onpopstate = null
}

Upvotes: 1

chri3g91
chri3g91

Reputation: 1410

/* Prevent accidental back navigation click */
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
    const leavePage = confirm("you want to go ahead ?");
    if (leavePage) {
        history.back(); 
    } else {
        history.pushState(null, document.title, location.href);
    }  
});

Upvotes: 12

span
span

Reputation: 5624

The solution by Robert Moore caused duplicate events when refreshing the page for me. Presumably since the state would be re-added multiple times.

I worked around it by only adding state if it is null. I also clean up the listener before going back.

    window.onload = function () {
        if (window.history && history.pushState) {
            if (document.location.pathname === "/MyBackSensitivePath") {
                if (history.state == null) {
                    history.pushState({'status': 'ongoing'}, null, null);
                }
                window.onpopstate = function(event) {
                    const endProgress = confirm("This will end your progress, are you sure you want to go back?");
                    if (endProgress) {
                        window.onpopstate = null;
                        history.back();
                    } else {
                        history.pushState(null, null, null);
                    }
                };
            }
        }
    };

MDN has a good read on managing state: https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method

Upvotes: 2

Robert Moore
Robert Moore

Reputation: 2572

Try this: it's simple and you get total control over the back button.

if (window.history && history.pushState) {
    addEventListener('load', function() {
        history.pushState(null, null, null); // creates new history entry with same URL
        addEventListener('popstate', function() {
            var stayOnPage = confirm("Would you like to save this draft?");
            if (!stayOnPage) {
                history.back() 
            } else {
                history.pushState(null, null, null);
            }
        });    
    });
}

Upvotes: 9

Manish Chauhan
Manish Chauhan

Reputation: 570

Try This,

window.onbeforeunload = function() {
  return "You're leaving the site.";
};
$(document).ready(function() {
  $('a[rel!=ext]').click(function() {
    window.onbeforeunload = null;
  });
});

Upvotes: -1

Robin Drexler
Robin Drexler

Reputation: 4457

It's possible to always display a confirmation box, when a user tries to leave the page. That also includes pressing the back button. Maybe that's a suitable quick-fix for your issue?

window.addEventListener('beforeunload', function() {
    return 'You really want to go ahead?';
}); 

http://jsfiddle.net/squarefoo/8SZBN/1/

Upvotes: 1

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

window.onbeforeunload = function() {
    return "Leaving this page will reset the wizard";
};

This would help you.

DEMO

Upvotes: 5

Related Questions