Test if links are external with jQuery / javascript?

后端 未结 13 1376
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for \"http\". I could just as
13条回答
  •  隐瞒了意图╮
    2020-11-28 05:51

    This doesn't exactly meet the "cannot hardcode my domain" prerequisite of the question, but I found this post searching for a similar solution, and in my case I could hard code my url. My concern was alerting users that they are leaving the site, but not if they are staying on site, including subdomains (example: blog.mysite.com, which would fail in most of these other answers). So here is my solution, which takes some bits from the top voted answers above:

    Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
      a.classList.add( a.hostname.includes("mywebsite.com") ? 'local' : 'external' );
    });
    
    $("a").on("click", function(event) {
      if ($(this).hasClass('local')) {
        return;
      } else if ($(this).hasClass('external')) {
        if (!confirm("You are about leave the  website.")) {
          event.preventDefault();
        }
      }
    });
    

提交回复
热议问题