I’m working on a particular process in a web application where the user could unintentionally create duplicate content using the browser back button. Here’s a handy way I ran across to disable the back button, or indeed handle it in any way needed.
12345678910111213141516171819202122232425262728
window.onload=function(){if(typeofhistory.pushState==="function"){history.pushState("jibberish",null,null);window.onpopstate=function(){history.pushState('newjibberish',null,null);// Handle the back (or forward) buttons here// Will NOT handle refresh, use onbeforeunload for this.alert('Back button disabled. Please use navigation links instead.');};}else{varignoreHashChange=true;window.onhashchange=function(){if(!ignoreHashChange){ignoreHashChange=true;window.location.hash=Math.random();// Detect and redirect change here// Works in older FF and IE9// * it does mess with your hash symbol (anchor?) pound sign// delimiter on the end of the URLalert('Back button disabled. Please use navigation links instead.');}else{ignoreHashChange=false;}};}}
Apparently, this works with older browsers that do not support HTML5.