2016-09-09 35 views
0

我想給rel="nofollow"發送我的外部鏈接,其內容由ckeditor管理。如何將rel =「nofollow」添加到CKEditor中的鏈接(如果它是外部鏈接的)

example.com =我的網站

externallink.com =任何外部鏈路

例如:

<p> 
    Lorem <a href="https://example.com/an-article.html">ipsum</a> dolar 
    <a href="http://externallink.com/example.html" rel="nofollow">sit</a> amet. 
</p> 

將該溶液:

editor.dataProcessor.htmlFilter.addRules(
{ 
    elements : 
    { 
     a : function(element) 
     { 
      if (!element.attributes.rel) 
       element.attributes.rel = 'nofollow'; 
     } 
    } 
}); 

https://stackoverflow.com/a/6930940/1848929nofollow添加到全部a元素。

如何只過濾外部鏈接?

約CKEditor的數據處理器還深DOC:http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Data_Processor


注:使用這​​些問題的答案#2的文本編輯器。在這個問題中檢查兩個鏈接的rel屬性。


我在我的頁面上使用cdn上的<script src="//cdn.ckeditor.com/4.5.10/standard/ckeditor.js"></script>

回答

0

我解決它就像;

CKEDITOR.on('instanceReady', function(ev) { 
     var editor = ev.editor; 
     editor.dataProcessor.htmlFilter.addRules({ 
       elements : { 
        a : function(element) { 
         if (!element.attributes.rel){ 
          //gets content's a href values 
          var url = element.attributes.href; 
          //extract host names from URLs 
          var hostname = (new URL(url)).hostname; 
          if (hostname !== window.location.host && hostname !=="youranothersite.com") { 
           element.attributes.rel = 'nofollow'; 
          } 
         } 
        } 
       } 
      }); 
    }) 
0

所以你需要比較主機,像這樣的東西應該工作。

a : function(element) 
    { 
     if (element.host !== window.location.host) { 
      element.attributes.rel = 'nofollow'; 
     } 
    } 
+0

但我的管理面板位於一個子域。如https://panel.example.com,您的解決方案是否涉及https://example.com? – hakiko

+0

而不僅僅是硬編碼你想要的主機而不是location.host – epascarello

+0

element.host在控制檯日誌 – hakiko

0

該解決方案還工作在Internet Explorer中:

CKEDITOR.on('instanceReady', function(ev) { 
    var editor = ev.editor; 
    editor.dataProcessor.htmlFilter.addRules({ 
     elements : { 
      a : function(element) { 
       if (!element.attributes.rel){ 
        //gets content's a href values 
        var url = element.attributes.href; 

        //extract host names from URLs (IE safe) 
        var parser = document.createElement('a'); 
        parser.href = url; 

        var hostname = parser.hostname; 
        if (hostname !== window.location.host) { 
         element.attributes.rel = 'nofollow'; 
         element.attributes.target = '_blank'; 
        } 
       } 
      } 
     } 
    }); 
}) 
相關問題