Preventing Back Button

From Logic Wiki
Jump to: navigation, search

Javascript Way

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function NoBack() {
    if (localStorage.getItem('isHistoryThere') == null || getCookie("UserCookie") === null) {
        localStorage.setItem('isHistoryThere', true);
    }

    if (getCookie("UserCookie") != null && getCookie('UserCookie').length > 1) {
        localStorage.setItem('isHistoryThere', true);
    }

    if (localStorage.getItem('isHistoryThere') === "false") {

        var foundIt = false;
        var safePages = ['Contact', 'Home', 'Forgot', 'Register'];
        if (document.URL.indexOf('/forms/') > 0) {
            foundIt = true;
        } else {
            for (var i = 0; i < safePages.length; i++) {
                if (document.title.split(" ")[0] === safePages[i]) {
                    foundIt = true;
                }
            }
        }
        if (!foundIt) {
            window.location = "/signin";
        }
    }
}

MVC Way

in global.asax

        protected void Application_BeginRequest()
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            Response.Cache.SetNoStore();
        }