Disable browser back button for one page applicati

2019-02-10 19:48发布

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) Please help! Thanks.

7条回答
Juvenile、少年°
2楼-- · 2019-02-10 19:54

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;
            }
        }
    });
}); 
查看更多
Root(大扎)
3楼-- · 2019-02-10 19:55

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"; };
查看更多
三岁会撩人
4楼-- · 2019-02-10 19:57

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

查看更多
太酷不给撩
5楼-- · 2019-02-10 19:57

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

查看更多
我命由我不由天
6楼-- · 2019-02-10 20:03

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.

查看更多
可以哭但决不认输i
7楼-- · 2019-02-10 20:11

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); };
查看更多
登录 后发表回答