Skip to content

Instantly share code, notes, and snippets.

@davehague
Last active November 15, 2024 16:55
Show Gist options
  • Save davehague/e2e59c9a8a5894fa774f6c7112d52108 to your computer and use it in GitHub Desktop.
Save davehague/e2e59c9a8a5894fa774f6c7112d52108 to your computer and use it in GitHub Desktop.
Have the marked (markedjs) library open links in new tab

In some cases I'd like the marked library open links in new tabs, but the default behavior is to open in the same tab. This means you have to override then renderer but the documentation doesn't make it completely obvious how to do that. Here's how you can do it.

// src/utils/markdown.ts
import { marked } from "marked";
import type { Token, Tokens } from "marked";

export const renderMarkdown = (content: string) => {
  try {
    const renderer = new marked.Renderer();
    renderer.link = ({ href, tokens }) => {
      const title = tokens
        .map((t: Token) => (t as Tokens.Text).text)
        .join(",");
      return `<a href="${href}" target="_blank" rel="noopener noreferrer">${title}</a>`;
    };

    return marked(content, { renderer });
  } catch {
    return content;
  }
};

Override the marked.Renderer's link functionality to use the target="_blank" rel="noopener noreferrer" syntax when creating links.

This is useful when creating links coming from markdown that you don't generate (in this case, from Todoist)

Then you can use it in your file:

import { renderMarkdown } from '../utils/markdown';

<p class="..." v-html="renderMarkdown(myMarkdownContent)"></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment