Solved

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

Posted on 2008-10-23
15
1,290 Views
Last Modified: 2010-05-18
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?
0
Comment
Question by:knowlton
  • 5
  • 5
  • 3
  • +2
15 Comments
 
LVL 19

Assisted Solution

by:bevhost
bevhost earned 50 total points
Comment Utility
0
 
LVL 8

Expert Comment

by:mkosbie
Comment Utility
Regarding pressing the back button/navigating from your page, see this other Q in progress (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23843168.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

0
 
LVL 44

Expert Comment

by:scrathcyboy
Comment Utility
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 !!
0
 
LVL 8

Expert Comment

by:mkosbie
Comment Utility
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.
0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
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.
0
 
LVL 8

Expert Comment

by:mkosbie
Comment Utility
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
0
 
LVL 44

Expert Comment

by:scrathcyboy
Comment Utility
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.


0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 44

Assisted Solution

by:scrathcyboy
scrathcyboy earned 150 total points
Comment Utility
sorry, the link has to have the right ID --  <A href=" " id="backlink"> click here to go back</A>
0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
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
}
0
 
LVL 8

Accepted Solution

by:
mkosbie earned 300 total points
Comment Utility
In IE, it's not ever firing the keypress or keyup events for a backspace.  It does fire the keydown event though.  FYI, in the HandleBackspace function, if you don't have the line return false, the page will still go back.  If you want the page to go back, use return true.  Try this:
var BACKSPACE = 8;

document.onkeydown = function(e) {

	if(!e) e = window.event;

	var key = e.keyCode ? e.keyCode : e.which;

	if(key == BACKSPACE) return HandleBackspace();

};
 

function HandleBackspace() {

	alert("Backspace clicked!");

	return false;

}

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
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"
0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
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

0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
Can we split the points among the participants?
0
 
LVL 8

Expert Comment

by:mkosbie
Comment Utility
0
 
LVL 1

Expert Comment

by:Vee_Mod
Comment Utility
Stopping auto-close by Asker request.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now