title: How to handle window.location.href event
body: <p>I'd like to know which is the location the page is trying to navigate (via Javascript) to and if it is <code>http://foo.com</code> I'd like to abort the redirection.</p>
  
  <p>Example:</p>
  
  <pre><code>function onredirect(url)
  {
     if(url == 'http://foo.com')
     { 
        abort();
     }
  }
  </code></pre>
  
  <p>I couldn't find a way to either handle the action let alone getting the target-url in an event handling parameter. Is it possible to :</p>
  
  <ul>
  <li>Listen to page changed event (<strong>as a result of</strong> <code>window.location.href</code> command) and</li>
  <li>Abort navigation if a specific URL is the target?</li>
  </ul>
  
  <p>The intention is that the snippet below does not navigate to the specified website: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function handleNavigation(urlDestination)
  { 
    
      alert('leaving to ' + urlDestination); 
      alert('Now a code for abortion should be executed if URL is foo.com'); 
  }
  
  window.onhashchange = handleNavigation;
  
  window.onunload =   handleNavigation ;
  window.addEventListener("beforeunload", function (e) {
      handleNavigation()
  }, false);
  window.addEventListener("unload", function (e) {
     handleNavigation()
  }, false);
  
  window.addEventListener('popstate', handleNavigation);
   
  
  window.onload = function(){
  
      window.location.href = 'http://foo.com'; //I want to know when this happened
  
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body onunload="handleNavigation()"&gt;
    &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The answer to this question will help me answer <a href="https://stackoverflow.com/questions/38161647/javascript-injection-prevention-on-wordpress/38162963#38162963">Javascript Injection prevention on Wordpress</a> .</p>
  
  <p>What I want is that if the user types <code>http://foo.com</code> he can leave. HOwever, if  a script redirects him to <code>http://foo.com</code>, I want to protect him from leaving to that place.</p>
  
  <p>Although this is similar to <a href="https://stackoverflow.com/questions/3522090/event-when-window-location-href-changes">Event when window.location.href changes</a> I want to see the target-url as a parameter. This could also be useful I wanted to log the pages the users are going to after leaving my website.</p>