Created
May 14, 2025 20:30
-
-
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").
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NPM
markdown-itpage: https://www.npmjs.com/package/markdown-it