Skip to content

Instantly share code, notes, and snippets.

@helloncanella
Created May 14, 2025 20:30
Show Gist options
  • Select an option

  • Save helloncanella/43df470fd717f2e57c608faeebdcaf60 to your computer and use it in GitHub Desktop.

Select an option

Save helloncanella/43df470fd717f2e57c608faeebdcaf60 to your computer and use it in GitHub Desktop.
Render Markdown links to open in a new tab (i.e., with target="_blank").
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Simple Markdown Renderer</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/markdown-it.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
const markdown = `
# Hello World
This is a [link to example.com](https://example.com)
`
const md = window.markdownit()
// Customize link rendering to add target="_blank"
const defaultRender =
md.renderer.rules.link_open ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options)
}
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const token = tokens[idx]
if (token.attrIndex("target") === -1) {
token.attrPush(["target", "_blank"])
}
if (token.attrIndex("rel") === -1) {
token.attrPush(["rel", "noopener"])
}
return defaultRender(tokens, idx, options, env, self)
}
// Render Markdown and insert it into the div
document.getElementById("content").innerHTML = md.render(markdown)
</script>
</body>
</html>
@helloncanella
Copy link
Author

helloncanella commented May 14, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment