title: Back button redirect script
body: <p>I am trying to develop a javascript code that when a user clicks on the back button of a webpage, it can be redirected to another URL.</p>
  
  <p>I have found these lines of code but I would like to know if there is something cleaner and more effective:</p>
  
  <pre><code>var bajb_backdetect={Version:'1.0.0',Description:'Back Button Detection',Browser:{IE:!!(window.attachEvent&amp;amp;&amp;amp;!window.opera),Safari:navigator.userAgent.indexOf('Apple')&amp;gt;-1,Opera:!!window.opera},FrameLoaded:0,FrameTry:0,FrameTimeout:null,OnBack:function(){alert('Back Button Clicked')},BAJBFrame:function(){var BAJBOnBack=document.getElementById('BAJBOnBack');if(bajb_backdetect.FrameLoaded&amp;gt;1){if(bajb_backdetect.FrameLoaded==2){bajb_backdetect.OnBack();}}bajb_backdetect.FrameLoaded++;if(bajb_backdetect.FrameLoaded==1){if(bajb_backdetect.Browser.IE){bajb_backdetect.SetupFrames()}else{bajb_backdetect.FrameTimeout=setTimeout("bajb_backdetect.SetupFrames();",700)}}},SetupFrames:function(){clearTimeout(bajb_backdetect.FrameTimeout);var BBiFrame=document.getElementById('BAJBOnBack');var checkVar=BBiFrame.src.substr(-11,11);if(bajb_backdetect.FrameLoaded==1&amp;amp;&amp;amp;checkVar!="HistoryLoad"){BBiFrame.src="blank.html?HistoryLoad"}else{if(bajb_backdetect.FrameTry&amp;lt;2&amp;amp;&amp;amp;checkVar!="HistoryLoad"){bajb_backdetect.FrameTry++;bajb_backdetect.FrameTimeout=setTimeout("bajb_backdetect.SetupFrames();",700)}}},SafariHash:'false',Safari:function(){if(bajb_backdetect.SafariHash=='false'){if(window.location.hash=='#b'){bajb_backdetect.SafariHash='true'}else{window.location.hash='#b'}setTimeout("bajb_backdetect.Safari();",100)}else if(bajb_backdetect.SafariHash=='true'){if(window.location.hash==''){bajb_backdetect.SafariHash='back';bajb_backdetect.OnBack();}else{setTimeout("bajb_backdetect.Safari();",100)}}},Initialise:function(){if(bajb_backdetect.Browser.Safari){setTimeout("bajb_backdetect.Safari();",600)}else{document.write('&lt;iframe id="BAJBOnBack" width="320" height="240" style="display: none;" src="blank.html" onunload="alert(\'de\')" onload="bajb_backdetect.BAJBFrame();"&gt;&lt;/iframe&gt;')}}};bajb_backdetect.Initialise();
  </code></pre>
  
  <p>and this is how you would use it in your HTML document:</p>
  
  <pre><code>&lt;script type="text/javascript" src="js/backfix.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;// &lt;![CDATA[
  bajb_backdetect.OnBack = function(){
      document.location.href = 'http://google.com'; //Change the url here with your desired URL
  }
  // ]]&gt;&lt;/script&gt;
  </code></pre>