11

I need to disable the back button of browser in my single page application. I tried using methods like onhashchange or window.history.forward but they don't work (reason may be that url doesn't get changed here)

Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
Developer107
  • 1,728
  • 2
  • 14
  • 24

8 Answers8

16

I work in AngularJS building a Single Page App and I wanted to disable or prevent the back button of the browser, because my app has buttons and anchors for all navegation into my app.

I searched and test many codes, and this is the easy to prevent the back button of browsers and the following code worked for me.

window.onpopstate = function (e) { window.history.forward(1); }

When the history detects the first history.back()

window.onpopstate

is executed, then after this moment any back or forward in history are detected for onpopstate event.

relizondo6
  • 184
  • 5
  • Thanks a lot. It worked well. Is there some way to disable refresh button too? – Developer107 Oct 03 '15 at 10:01
  • This is working fine but in another case i am using window.history.back() by button click for previous page. it is stopping this one also staying on the same page, not going back. how can i resolve? – Sreekanth Karini Sep 09 '16 at 08:14
  • I used this approach but state of application is changed but the url is unchanged! any idea ? – Rathma Dec 19 '17 at 06:26
7
import { LocationStrategy } from '@angular/common';  
 constructor( private location: LocationStrategy){  
// preventing back button in browser implemented by "Samba Siva"  
history.pushState(null, null, window.location.href);
this.location.onPopState(() => {  
history.pushState(null, null, window.location.href);
});  
}
3

I dont think disabling the back button will really work. So many reasons for same but have look at this. Your best solution will be warn the user using

window.onbeforeunload = function() { return "You will  leave this page"; };
Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
3

You technically cannot disable the Back button on someone's browser, however, you can make it so that the button isn't available or continues to load the same page.

You can check it here Disabling the Back Button

Shekhar
  • 812
  • 1
  • 8
  • 18
  • 1
    I can't reload the same page as session is getting involved hence includes complexities. How can I make the button unavailable? – Developer107 Jul 09 '15 at 07:02
  • you can do this by using javascript [Disabled](http://www.htmlgoodies.com/tutorials/buttons/article.php/backbutton.html) – Shekhar Jul 09 '15 at 07:30
  • Didn't get anything on this link besides this message: We were unable to find the page you asked for on HTMLGoodies.com. – Developer107 Jul 09 '15 at 09:54
  • just right click on this link and select open link in new tab. only to show you the effect. – Shekhar Jul 09 '15 at 10:35
2

You can redirect same page on click of back button, your page will get refreshed but you will be on the same page every time

Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
1

i think the "onpopstate" dont work if the user persist click

just use

window.onbeforeunload = function() { window.history.forward(1); };

or if u like to warning user

window.onbeforeunload = function() { return "Back button is not available!"; window.history.forward(1); };
Deivi
  • 197
  • 2
  • 12
1

If you're using AngularJS, the following code should do the trick. You have to add this code to app.js file or file where you inject all your dependencies

var myApp = angular.module('myApp', ['ngMask', 'ngRoute', 'ngAnimate', 'ngSanitize', 'ngTouch', 'ngCookies', 'ngMessages', 'ui.router', 'ui.grid', 'ui.directives', 'ui.filters', 'ui.bootstrap', 'angularUtils.directives.dirPagination']);
myApp.run(function($rootScope, $route, $location) {
    var allowNav = false;
    var checkNav = false;

    $rootScope.$on('$stateChangeSuccess', function (event, toState, toStateParams, fromState, fromStateParams) {
        allowNav = checkNav;
        checkNav = true;
    });

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        // Prevent the browser default action (Going back)
        if (checkNav) {
            if (!allowNav) {
                event.preventDefault();
            } else {
                allowNav = false;
            }
        }
    });
}); 
Victor
  • 3,669
  • 3
  • 37
  • 42
0

I had a different scenario where we wanted to blacklist a few pages. Allowing most of the SPA to use the back button and a few pages to not allow it. I created a service to override the functionality of the popstate. However I ran into a weird issue with going forward.

import { RouteAddress } from 'app/common/constants/routes.constants';
import { Injectable } from '@angular/core';
import { StringUtilsService } from 'app/common/services/utilities/string-utils.service';

@Injectable()
export class LocationStrategyService {
    private static shouldSkip = false;
    // Array of route urls that we can't go back to.
    private static blackListed = [
        RouteAddress.ScreeningStepTwoCreditAvailability,
        RouteAddress.ScreeningStepTwo];

    constructor() {
        window.onpopstate = this.overridingPopState;
    }

    overridingPopState(event: any) {
        // This was having issue scoping
        const isBlackListed = (navigatingTo: string): boolean => {
            navigatingTo = navigatingTo.split('?')[0];
            const pathFound = LocationStrategyService.blackListed.find((route) => navigatingTo.endsWith('/' + route));
            return pathFound !== undefined && pathFound.length > 0;
        }

        // have black listed route and determing if able to go back
        if (!LocationStrategyService.shouldSkip && isBlackListed(event.currentTarget.location.pathname)) {
            window.history.forward();
            // Protecting against a going forward that will redirect
            LocationStrategyService.shouldSkip = isBlackListed(window.location.pathname);
        } else {
            LocationStrategyService.shouldSkip = false;
        }
    }
}

Then in your AppComponent constructor add the LocationStrategyService and it will call it on start.

import { LocationStrategyService } from 'app/common/services/utilities/location-strategy.service';
export class AppComponent {


  constructor(        
  private locationStrategyService: LocationStrategyService) {}
}
DeadlyChambers
  • 5,217
  • 4
  • 44
  • 61