Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

Detecting when user hits "Backspace" or navigates to previous page

How do I do this in JavaScript:

Detect when user hits "Backspace" or navigates to previous page?

Can I trap keypresses in JavaScript?  Or what is the best approach for this?
SOLUTION
Avatar of David Beveridge
David Beveridge
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mkosbie
mkosbie

Regarding pressing the back button/navigating from your page, see this other Q in progress (https://www.experts-exchange.com/questions/23843168/Browser-Back-Button.html).  Specifically to capture the keypress, you want to use the onkeypress/onkeydown/onkeyup events.  Something like the attached code:
var BACKSPACE = 8;
 
window.onkeyup = function(e) {
    if(!e) e = window.event;
 
    var key = e.keyCode ? e.keyCode : e.which;
    if(key == BACKSPACE) yourBackspaceFunction();
};

Open in new window

that doesn't detect a mouse click on the back button, or a hot key customized by the user to go back.  In short, the answer to your question, I believe, is that YOU CANNOT DETECT THIS !!
As explained in the Q I referenced in my original answer, you can handle the window.onbeforeunload event.  That event fires when your page is closed for ANY reason.  See the Q for a further explanation.
Avatar of Tom Knowlton

ASKER

There may be more than one way to skin a cat here.

I think what I need (on the page in question) is to know what page I just came from.  Then I need to detect when I go back to that page, and (perhaps) if the Backspace key was what instigated the "go back" action.

Then when I go back to the page I just came from, depending on the page, I need to tell that page that I am coming FROM the page I just came from.


What I am driving at is this.  I have a page that displays some search results.  Each search result has a hyperlink that takes me to another page.  On the other page, when I click "go back" or press the Backspace key or do any action that takes me back to the page I came from -- I need to know.
Generally, you would use the document.referrer property to accomplish this.  The problem is, when you go back in a browser, the referrer isn't reset to the page you're coming back from, it's left at it's value when the page you go back to was first loaded.  That makes it pretty useless in this case.

Also, because as we discussed, there's no effective way to know when a user goes back on a page (as opposed to closing it, going to a different page, etc), you won't be able to trap the back event either.

You might be able to put together a solution as follows:
   1) Disable caching of your search results page (to prevent going back)
   2) Provide your own "Back to results" link on all result pages
   3) Put special code on the links to tell the previous page where you're coming from
that's a totally different consideration than using the back button, which you cannot control.  Getting the page you came from is as simple as doing this --

in javascript --

function GetPrevPage()  {
if (document.referrer&&document.referrer!="") {
  var prevPage= document.referrer;
  document.getElelmentById('backlink').href=prevPage;
  }
}

in HTML

<A href=" " > click here to go back</A>

So you can put that function call in an onClick, or maybe better --

<BODY  onLaod="getPrevPage();" >

that way the previous page link is set every time you load a page.

You can also use onbeforeunload(), which activates when you leave a page.


SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Going back to the keypress approach.

I can detect regular keypresses like "t" or "w" but the backspace key does not fire:

function HandleBackButton(current) {
              e = window.event;
              var key = e.keyCode;
              alert(key);  // Does not work with "Backspace" keypress
}
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I need to check if the focus is on a control like a textbox or radiobutton when backspace is pressed.

For example ...  in a textbox a backspace should erase to the left ... not invoke "previous page in history"
This seems to do the trick (see snippet):
	// function to possibly override keypress
  	trapfunction = function(event) {
  		var keynum;
 
  		if (window.event) // eg. IE
  		{
  			keynum = window.event.keyCode;
  		}
  		else if (event.which) // eg. Firefox
  		{
  			keynum = event.which;
  		}
 
  		// backspace has code 8
  		if (keynum == 8) {
  			if ((document.activeElement.getAttribute("type") === "text") | (document.activeElement.getAttribute("type") === "textarea")) {
  				return true;
  			}
  			else {
  				__doPostBack('', 'BACKSPACE');
  			} 			
  		}
 
  		return true;
 
 
	document.onkeydown = trapfunction; // IE, Firefox, Safari
	document.onkeypress = trapfunction; // only Opera needs the backspace nullifying in onkeypress
  

Open in new window

Can we split the points among the participants?
Stopping auto-close by Asker request.