kramdown
kramdown copied to clipboard
Feature request: default options for generated html tags
Hi,
I'm using kramdown for static site generation and I have lots of links / anchor tags in my outputted html. When a user clicks on one of my external links, the new window's javascript has access to my opening window and can redirect it to a phishing page. The full details for this issue are documented here: https://mathiasbynens.github.io/rel-noopener/
The fix for this is to generate links like <a href="url" rel="noopener">title</a>
, which ensures that window.opener
is null in the new window. Right now I'm adding this to all my links manually using kramdown's span IAL: [title](url){:rel="noopener"}
. However this gets tedious and error-prone as there are so many links. Would it be possible to get a config option for default attributes on outputted html elements? I imagine this could be useful for other cases as well - applying classes to generated output for styling, etc.
The standard way to customize this would be to adapt the HTML converter to your needs since this is something very specific.
However, it might be useful if such a functionality would indeed exist for all elements. I'm just not quite sure if this is really the case.
@arkadiyt For now, you can post-process the HTML with e.g. Nokogiri:
html = Nokogiri::HTML.fragment(html).tap do |doc|
doc.css('a').each do |node|
node['href'] ||= '#'
# Add attributes to external links only:
if node['href'] =~ %r{\A(?:\w+:)?//}
node['target'] = '_blank'
node['rel'] = 'nofollow noopener'
end
end
end.to_html
This seems to apply only to links augmented with target="_blank"
. In my experiments, if I open a non-augmented link in a new tab via context menu, window.opener
is null
.
In some of my kramdown texts, I have abbreviations in use like the following:
{:n: target="_blank"}
So I just need to append {:n}
.
One can do likewise for links to untrusted targets:
{:xn: target="_blank" rel="nofollow noreferrer noopener"}
and then just append {:xn}
where applicable.
My point is: This seems to apply only to links that you have already an IAL for, so you just have to change that IAL, not provide new ones.
ccorn: I didn't realize you could alias the attributes like that, thanks for the tip.
glebm: The postprocessing approach is what I ended up using - it was simpler to me than figuring out adapting the html converter and making that into a jekyll plugin.
I still think it might be a useful feature but I understand if it gets closed as won't fix
One thing: If this were implemented, it would have some performance impact on the conversion because there would need to be additional checks for each and every element. However, I don't think that the impact would be great.