[英]How to add rel=“nofollow” attribute to external links in PageDown.js?
I'm using PageDown.js to make raw HTML in markdown style like StackOverflow does. 我正在使用PageDown.js来制作像StackOverflow那样的markdown风格的原始HTML。 My code looks like the following in nodejs: 我的代码在nodejs中如下所示:
var saneConv require('./pagedown/Markdown.Sanitizer'),
resultHTML = saneConv.makeHtml('[raw html string]');
Now I need to add rel="nofollow"
to all external links. 现在我需要将rel="nofollow"
添加到所有外部链接。 Unfortunately I can't see that ability in PageDown itself. 不幸的是,我无法在PageDown中看到这种能力。
Could you advice me please a solution to add ref="nofollow"
attribute to all external links? 你可以建议我为所有外部链接添加ref="nofollow"
属性的解决方案吗?
If all links are external then you could simply use 如果所有链接都在外部,那么您可以简单地使用
resultHTML = resultHTML.replace('<a ', '<a rel="nofollow" ');
or there's a function called writeAnchorTag in Markdown.Converter.js that you can change to do what you need. 或者在Markdown.Converter.js中有一个名为writeAnchorTag的函数,您可以将其更改为执行所需操作。
Update 更新
var jsdom = require("jsdom");
var fs = require("fs");
var jquery = fs.readFileSync("./path/to/jquery.js", "utf-8");
var saneConv = require('./pagedown/Markdown.Sanitizer'),
resultHTML = saneConv.makeHtml('[raw html string]');
jsdom.env(resultHTML, [jquery], function(err, window) {
var $ = window.$;
$("a").each(function() {
var $a = $(this);
var href = $a.attr('href');
// figure out if href is external or internal
// let's say if href doesn't contain specific domain it's external so add rel=nofollow
if (href.indexOf('example.com') < 0 || href.indexOf('example2.com') < 0) {
// it's external, let's add rel=nofollow
$a.attr('rel', 'nofollow');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.