最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When window.onbeforeunload is called, can I know where the page is being redirected to? - Stack Overflow

programmeradmin0浏览0评论

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
       }
});

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
       }
});
Share Improve this question edited Dec 12, 2022 at 8:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 15, 2011 at 6:58 NeerajNeeraj 8,5328 gold badges43 silver badges71 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论