Warn and confirm to the User, if Back button is pressed
is as below -
window.onbeforeunload
= function() { return
"Your data will be lost!";
};
You can also add hash when page is loading –
location.hash
= "noBack";
Then just handle location hash change to add
another hash –
$(window).on('hashchange',
function() {
location.hash
= "noBack";
});
That makes hash always present and back button
tries to remove hash at first.
The Events
–
<script
type="text/javascript">
function handleBackFunctionality()
{
if
(window.event)
{
if
(window.event.clientX
< 40 && window.event.clientY
< 0) {
alert("Clicked
- Browser back button.");
}
else
{
alert("Clicked
- Browser refresh button.");
}
}
else
{
if
(event.currentTarget.performance.navigation.type
== 2) {
alert("Clicked
- Browser refresh button.");
}
else
if (event.currentTarget.performance.navigation.type
== 1) {
alert("Clicked
- Browser back button.");
}
}
}
window.onbeforeunload
= handleBackFunctionality;
$(document).unload(handleBackFunctionality);
</script>
It is very easy to disable the browser BACK
button, like the JQuery code –
<script
type="text/javascript">
//History APIs.
if( window.history
&& window.history.pushState
){
history.pushState(
"nohb", null,
"" );
$(window).on(
"popstate",
function(event){
if(
!event.originalEvent.state
){
history.pushState(
"nohb", null,
"" );
return;
}
});
}
</script>
Using the hashchange
Event –
<script
type="text/javascript">
var hashChangedCount
= -2;
$(window).on("hashchange",
function () {
hashChangedCount++;
if
(top.location.hash
== "#main"
&& hashChangedCount
> 0) {
alert("Hi!");
}
top.location.hash
= '#main';
});
top.location.hash
= "#";
</script>
OR
<script
type="text/javascript">
$(window).bind('hashchange',
function() {
top.location
= '#main';
// Eventually alert
the user describing what happened.
});
</script>
Using ASP.NET
MVC 5 and C# -
//ASP.NET MVC 5/C# code
var
currentPageUrl = Session["CurrentPage_URL"];
if
(currentPageUrl != null)
{
Session["PreviousPage_URL"]
= Session["CurrentPage_URL"];
}
Session["CurrentPage_URL"]
= Request.Url;
And
<script
type="text/javascript">
//Handle Back Functionality.
function handleBackFunctionality()
{
var
previousPageUrl = "@Session["PreviousPage_URL"]";
if
(document.referrer
== previousPageUrl)
{
alert("Its
a back button click...");
//TODO - code
here...
}
}
</script>