Here we'll talk about technology. Ask questions about technology and I'll answer the questions and will post them here! Any questions can be mailed at techbiztalk@gmail.com

Wednesday, April 30, 2008

Detecting Browser Back Button using "javascript"

To start with, "there is no method in javascript to detect a back button pressed in browser".

The above statement is good enough to scare anyone who wants to have some functionality specifically when a user clicks on the BACK button in their browser. But I am here to tell the solution to this problem. So here it goes.

Well.. the above statement is true in case of a website where no server side code is to be used. We can implement a solution with both Server side code (like ASP/JSP/.NET/PHP etc.) and client side (i.e. javascript or vbscript)

The solution is simple. Whenever we are on a page, add that page URL to a session or an request variable as current page. Now whenever we move to another page, get the current page from session/request, save that as previous page in another session/request variable and save the current page again as current session/request variable.

Now checkout the onbeforeunload event of javascript. This event is fired whenever the page is about to unload to give way to another page. This could happen whenever a refresh button is pressed or back or forward button or any submit event from page or even clicking on a link.

When the event is fired, check whether the javascript object document.referrer is having the same value as the previous page variable in session/request. If it is, definitely back button is pressed.

:)

Following is the code in JSP and javascript.

JSP
currPage = session.getAttribute("currPage");
prevPage = currPage;
currPage = request.getRequestURI();
session.setAttribute("currPage", currPage);
session.setAttribute("prevPage", prevPage);



javascript:
var prevPage = "<%=prevPage%>"
onbeforeunload = function() {
if(document.referrer == prevPage) {
alert("Back Button Pressed");
// Do Whatever here
}
}


Enjoy.....

Labels: , , , , , , , , , , , , , , ,

 

 

 

2 Comments:

Blogger Health and fitness said...

NOT WORKING

January 28, 2014 at 5:06 PM

 
Anonymous Anonymous said...

What russbis...

September 30, 2014 at 7:35 PM

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home