【问题标题】:Check if link is from an external Domain检查链接是否来自外部域
【发布时间】:2020-03-23 10:04:07
【问题描述】:

我正在使用 Laravel 和 jquery。我有电子商务,我有我的产品列表,其中一些在我的网站上,其中一些我不需要 重定向在我的网站内的产品其他人打开一个新标签。 例如:

<a href="www.MYWEB.COM" > MY PRODUCTS</a>

<a href="https://www.w3schools.com" target="_blank"> Producs from other website </a>

有可能吗?到目前为止,我有这个。我真的需要帮助。

<div class="dropdown-menu dropdown-menu-right">
   <div class="header-items">My Products<span class="count-items ml-1">{{count($notifications)}}</span></div>
     @foreach ($notifications as $item)
       <a href="{{ $item->url }}"  class="idNote" data-note="{{ $item->id }}" style="color: #000000;" data-redirect="{{$item->url}}">
         <div id="note-{{ $item->id }}" class="item {{$item->isOpen? 'not-read' : '' }}"  >
              <p class="mb-0 font-medium">{{ $item->titulo }}</p>
              <p class="mb-0">{{ $item->texto }}</p>
              <span class="point-not-read"></span>
         </div>
       </a>
     @endforeach                   
</div>

我的 jquery

<script>
    $('.idNote').click(function(e){
        e.preventDefault();

        var noteId = $(this).attr('data-note');
        var redirecTwo = $(this).attr('data-redirect');
        console.log(noteId);
        $.ajax({
            url : "{{ route('readit') }}",
            type : "POST",
            data : {
                jsNoteId : noteId
            },
            beforeSend : function(){
                $('#note-'+noteId).removeClass('not-read');
                //window.location = redirecTwo;
                window.open(redirecTwo, '_blank');
            },
            success : function(r){                    
                console.log(r);                    
            }
        });
    });
</script>

【问题讨论】:

    标签: jquery html laravel-5 redirect http-redirect


    【解决方案1】:

    您可以检查href是否包含您的网站名称

    $('.idNote').click((e)=>{
       e.preventDefault();
       let href = $(e.target).attr('href');
       let mySiteName = 'https://NAME OF YOUR SITE.com';
       if(href.includes(mySiteName){
          window.open(href, '_self')
       }else{
          window.open(href, '_blank')
       }
    })
    

    【讨论】:

      【解决方案2】:
      1. 创建 href 属性的实际 URL
      2. 检查url.hostname 是否与我们网站的主机名匹配
      3. 如果匹配,则在当前选项卡中打开窗口
      4. 如果没有,则在新标签页中打开窗口

      例如。

      $('.idNote').click(function(e){
          e.preventDefault();
          var href = $(this).attr('href');
          href = href.startsWith("http") ? href : "http://"+href;
          href = new URL(href);
          if((href.hostname).startsWith("www.myweb.com")){ //use this if statement in your beforeSend function
          window.open(href);
      }else{
          window.open(href,"_blank");
      }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多