how to detect if a link was clicked when [removed] is triggered?

前端 未结 3 987
半阙折子戏
半阙折子戏 2020-12-02 00:13

I have window.onbeforeunload triggering properly. It\'s displaying a confirmation box to ensure the user knows they are navigating (closing) the window and that any unsaved

相关标签:
3条回答
  • 2020-12-02 01:02
    var link_was_clicked = false;
    document.addEventListener("click", function(e) {
      if (e.target.nodeName.toLowerCase() === 'a') {
        link_was_clicked = true;
      }
    }, true);
    
    window.onbeforeunload = function() {
      if(link_was_clicked) {
        link_was_clicked = false;
        return;
      }
      //other code here
    }
    
    0 讨论(0)
  • 2020-12-02 01:05

    You're looking for deferred event handling. I'll explain using jQuery, as it is less code:

    window._link_was_clicked = false;
    window.onbeforeunload = function(event) {
      if (window._link_was_clicked) {
        return; // abort beforeunload
      }
      // your event handling
    };
    
    jQuery(document).on('click', 'a', function(event) {
      window._link_was_clicked = true;
    });
    

    a (very) poor man's implementation without jQuery's convenient delegation handling could look like:

    document.addEventListener("click", function(event) {
      if (this.nodeName.toLowerCase() === 'a') {
        window._link_was_clicked = true;
      }
    }, true);
    

    this allows all links on your page to leave without invoking the beforeunload handler. I'm sure you can figure out how to customize this, should you only want to allow this for a specific set of links (your question wasn't particularly clear on that).

    0 讨论(0)
  • 2020-12-02 01:05

    You can differ between a link unload or a reload/user entering a different address unload s by using a timer. This way you know the beforeunload was triggered directly after the link click.

    Example using jQuery:

    $('a').on('click', function(){
      window.last_clicked_time = new Date().getTime();
      window.last_clicked = $(this);
    });
    
    $(window).bind('beforeunload', function() {
      var time_now = new Date().getTime();
      var link_clicked = window.last_clicked != undefined;
      var within_click_offset = (time_now - window.last_clicked_time) < 100;
    
      if (link_clicked && within_click_offset) {
        return 'You clicked a link to '+window.last_clicked[0].href+'!';
      } else {
        return 'You are leaving or reloading the page!';
      }
    });
    

    (tested in Chrome)

    0 讨论(0)
提交回复
热议问题