Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Created February 26, 2022 22:17
Show Gist options
  • Save TerribleDev/67070955700f28a6c0d4010d5b8ce7c3 to your computer and use it in GitHub Desktop.
Save TerribleDev/67070955700f28a6c0d4010d5b8ce7c3 to your computer and use it in GitHub Desktop.
A markdig extension to add norel and noopener to external links
public class TargetLinkExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
var htmlRenderer = renderer as HtmlRenderer;
if (htmlRenderer != null)
{
var inlineRenderer = htmlRenderer.ObjectRenderers.FindExact<LinkInlineRenderer>();
if (inlineRenderer != null)
{
inlineRenderer.TryWriters.Remove(TryLinkInlineRenderer);
inlineRenderer.TryWriters.Add(TryLinkInlineRenderer);
}
}
}
private bool TryLinkInlineRenderer(HtmlRenderer renderer, LinkInline linkInline)
{
if (linkInline.Url == null)
{
return false;
}
Uri uri;
if (!Uri.TryCreate(linkInline.Url, UriKind.RelativeOrAbsolute, out uri) || !uri.IsAbsoluteUri)
{
return false;
}
RenderTargetAttribute(renderer, linkInline);
return false;
}
private void RenderTargetAttribute(HtmlRenderer renderer, LinkInline linkInline)
{
linkInline.SetAttributes(new HtmlAttributes() { Properties = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("target", "_blank"), new KeyValuePair<string, string>("rel", "noopener"), } });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment