Link to home
Start Free TrialLog in
Avatar of Swatantra Bhargava
Swatantra BhargavaFlag for India

asked on

Browser Back Button

Hello Experts,

I am trying to use browser back button to go to a specific URL. I used PlatformLocation in Angular to detect the popstate event. When I press the back button to go to the URL, it shows the previous angular route for fraction of seconds and then redirects me to the URL. I would like to eliminate that fickle from back button. So, it directly goes to the desired URL, without going to the previous angular route.

Thanks in advance.
Avatar of Debasis Saha
Debasis Saha
Flag of India image

You can check the below code -

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);
            }
        });    
    });
}
Avatar of Swatantra Bhargava

ASKER

Below is my function in Angular JS by which I want to do the same:

this.location.onPopState(() => {

	if (this.router.url === '/success') {
		
		let checkoutUrl = "https://www.google.com/";
		window.document.clear();
		window.location.replace(checkoutUrl);

		document.write('<meta http-equiv="refresh" content="0; url=' + checkoutUrl + '" />');
		$(location).attr('href', checkoutUrl);

		let link = document.createElement('a');
		link.href = checkoutUrl;
		document.body.appendChild(link);
		link.click();

		return false;
	}
});

Open in new window

Suppose I came on success page from the checkout page. What I want when I click on browser's back button, window open google.com but what this code is doing it opens checkout page first for a while and after that control goes to google.com

Hope you understand.
Yes I understand your problem.. I will check and give u feedback on your code..
Is there Anyone who can guide me?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.