Display a warning when leaving the site, not just the page

前端 未结 7 796
旧时难觅i
旧时难觅i 2020-12-05 20:55

This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible t

相关标签:
7条回答
  • 2020-12-05 21:27

    This may help

    1. You need to check onclick event before attach initLocalLinkException();
    2. Disclaimer: It's not tested.

    HTML:

    <a href="test.html">internal link</a>
    <a href="#test">html anchor</a>
    <a href="http://www.google.com">external link</a>
    <a href="http://www.google.com" target="_blank">blank external link</a>
    <form action="test.html" method="post" >
        <button type="submit">Post Button</button>
    </form>
    

    JavaScript:

    $(document).ready(function () {
      initLocalLinkException();
      window.onbeforeunload = function () { confirmExit() };
      $('form').submit(function () { 
        window.onbeforeunload = null;
      });
    });
    
    function initLocalLinkException() {
      $('a').click(function () {
        if ($(this).attr('target') != '_blank') {
    
          var link = $(this).attr('href');
          if (link.substr(0, 4) == 'http') { 
            var LocalDomains = new Array('http://www.yourdomain.com', 
                                         'https://yourdomain.com', 
                                         'localhost', '127.0.0.1');
            var matchCount = 0;
            $.each(LocalDomains, function () {
              if (this == link.substr(0, this.length)) {
                matchCount++; 
              }
            });
            if (matchCount == '0') { 
              confirmExit(); 
            } else {
              window.onbeforeunload = null;
            }
          } else { window.onbeforeunload = null;  }
    
        }
      });
    }
    
    function confirmExit() {
      alert('Are you sure?'); // Do whatever u want.
    }
    
    0 讨论(0)
提交回复
热议问题