4

Whenever I add an event listener window.onbeforeunload, can I check where the page is being redirected to? Or at least what the developer is trying to change.

The following is the thing that I really want:

This is what I do right now :

$(window).bind("beforeunload",function(){
      //I do what I want here
});

Now the issue is, I want to change the logic, when document.location.href = "mailTo:*" is being called. i.e. I do not want to do anything when doccument.location.href is called, so I want my logic to me like:

$(window).bind("beforeunload",function(){
       if(document.location.href has mailTo:)
       {
            //do nothing
       }
       else
       {
            //my old logic applies here
       }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Neeraj
  • 8,408
  • 8
  • 41
  • 69

1 Answers1

4

You would need to add an event handler to Href links in your webpage, which set a variable on onclick = their href, you can read that variable in your onbeforeunload script. example code would be like this :

  var storeHref = null;
    $("a").bind("click", function(){
      storeHref = this.href;
      return true;
    });

  $(window).bind("beforeunload",function(){
       if(storeHref has mailTo:)
       {
            //do nothing
       }
       else
       {
            //my old logic applies here
       }
  });

However if the redirection is happening due to some other event,like user entering a new url in the browser, or using a script, you can not detect the destination due to security reasons.

Similar: How can i get the destination url in javascript onbeforeunload event?

Community
  • 1
  • 1
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • 2
    the case here actually is not the user clicking a link, but the developer calling document.location.href="mailTo", or document.location.href="someotherlink" – Neeraj Mar 15 '11 at 07:06
  • 1
    that seems not possible then, see http://stackoverflow.com/questions/1686687/how-can-i-get-the-destination-url-in-javascript-onbeforeunload-event – DhruvPathak Mar 15 '11 at 07:17
  • can you please update the answer so that I can accept it as the correct one? – Neeraj Mar 15 '11 at 07:28