Javascript: Escape key = browser back button

Ryan picture Ryan · Jun 17, 2011 · Viewed 13.1k times · Source

In a browser how can I make the keyboard's escape key go back in Javascript.

For example: if you visit this page and click the "Fullscreen" link I'd like to press the escape key and go back to the previous page.

What's the Javascript to make this magic happen?

Answer

Floern picture Floern · Jun 17, 2011

You can add a Key-Listener:

window.addEventListener("keyup", function(e){ if(e.keyCode == 27) history.back(); }, false);

This will call history.back() if the Escape key (keycode 27) is pressed.