Can I create links with 'target="_blank"' in Markdown?
Asked Answered
G

24

788

Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.

Gibeonite answered 13/12, 2010 at 1:33 Comment(3)
So as pointed out in the answers, it is not a feature in markdown. If you wanted to make this a default sitewide to link out, David Morrow has the answer. Or if you just wanted to do it in one instance, then Matchu's answer says that you must actually write that in HTML.Thumbscrew
possible duplicate of Markdown open a new window linkPietra
Your question isn't specific about what you're doing, but some markdown engines or browsers (not sure which) recognize when the link you're creating is pointing to a different domain and will open those in a new tab. For me, there are times when removing the s from the https: is enough to get the functionality I want.Caecilian
A
587

As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.

<a href="http://example.com/" target="_blank">Hello, world!</a>

Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.

If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.

Abruption answered 13/12, 2010 at 1:40 Comment(12)
Ya know what? I agree with you and alex. I decided not to use _blank at all. It's a better user experience to keep things in one browser. They can just hit back or command-click (Mac user here :)), like you say.Gibeonite
I have javascript run on the page that adds _blank to all links outside of my domain. like @alex has in the next answerCementation
I would suggest (in the desire of being explicit and inline readable) the following syntax: [Visit this page](http::/link.com( to get the idea of opening.Windsucking
Simple target="_blank" may be dangerous! Add also rel="noopener" into the tag! (sites.google.com/site/bughunteruniversity/nonvuln/…)Azaleeazan
@MaxVyaznikov Interesting. Do you think it would be safer if browsers provided an above the edge pop up window for login? Separate the login UI for websites from spoofed and fake login UI created by "lookalike" web pages. It might be more possible now where it was more difficult in the past.Lynelllynelle
Concerning hitting the back button... with Rmarkdown, in my experience if the link is not found, the back button closes the app/doc completely.Landau
unfortunately the <a> tag using target="_blank" did not work for me, opens the link the same tab :( At least when the file was on github.Telamon
This doesn't work in markdown, it still opens in the same tab.Letsou
Would be a great answer, but does not work on github Wiki pages (which unconditionally strips out target="_blank", possibly due to possibly unfounded security concerns).Witcher
It's really not always a better user experience to keep things in one browser... What if they are in a sign-up or check-out flow in your SPA, and at the last step they need to agree to some conditions in an external page? Unless you use a modal, opening in a new window would really be preferable to the user completely losing context and having to go through the whole process again.Carrolcarroll
@DaveLand, before stating something is unfounded best to do a little research. This little sample page of possible issue may be an eye-opener if you haven't got latest/greatest browsers: mathiasbynens.github.io/rel-noopenerSeminarian
@DaveLand I'd just like to take a minute to say hi to another Dave Land (my name too). I've never met one before! You seem quite handsome and clever. At first I read your comment and thought "man I don't remember making that comment". Then I was like "wait, my stack overflow username is not Dave Land". Then I realized I'm not as alone in the universe as I thought...sniff...Lamelliform
R
521

Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:

[link](url){:target="_blank"}
Reames answered 16/1, 2011 at 13:40 Comment(13)
This does not seem to work using the Markdown engine on Mac :-(Iny
I didn't wanna use html inside markdown, it really looks a bit nasty. But this method is awesome. Thank You!Cist
Works great with jekyll!Ulaulah
The kramdown syntax: [link name](url_link){:target="_blank"} can be parsed into HTML using the kramdown online editor: http://trykramdown.herokuapp.com/ I used it because I already had quite a few kramdown references, and wanted to avoid retyping them.Alphabetize
Is there a way in jekyll to set this as the default? I'd like all the links in my blog posts to open with target="_blank"Clearstory
It doesn't work. It just renders the {:target="_blank"} as text.Letsou
The reason this doesn't work is that (at least in vscode) '' is interpreted as the beginning of a span of italic text. When there is no closing '', it malprocesses the md.Cameliacamella
for those who are interested: this does not work neither for Jupyter Notebook nor for Python Dash (version 0.39.0)Shalne
Works great with Pelican ! Tx !Cadet
In Safari running JupyterHub, no need for the {:target="_blank"}.Rozella
It works without the colon ':' for me: [link](url){target="_blank"} I use lume as a site generator, it uses markdown-it rpm package.Intractable
This did the trick! For using with pandoc, you can just pipe it like so: kramdown myfile.md | pandoc -o myfile.html -f markdown -t htmlDionisio
This doesn't work out of the box with Wiki.js for those curious.Wedding
S
135

I don't think there is a markdown feature, although there may be other options available if you want to open links which point outside your own site automatically with JavaScript.

Array.from(document.links)
    .filter(link => link.hostname != window.location.hostname)
    .forEach(link => link.target = '_blank');

jsFiddle.

If you're using jQuery:

$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');

jsFiddle.

Shanitashank answered 13/12, 2010 at 1:37 Comment(9)
i agree with you but on the occasion that you are in an iframe you need to blast out of the frame with the link.Semitropical
I find the only time I force people into a new window is when I'm halfway through a sentence linking somewhere external, and I want to provide sources for my comments without interrupting the flow. This js snippet is ideal for the purpose - thanks, upvoted :)Germain
I think that quote from Jakob Nielson doesn't apply here anymore. He complains about opening new windows, but nowadays target="_blank" opens in a new tab instead. I personally don't like it when links to other domains don't open in new tabs.Revelry
Because he clearly doesn't understand, or appreciate, the importance of style and design for usability - which when taken seriously may well conflict with some of the mechanistic concepts he is so fond of. He fails to see that building a great website requires humble pragmatism much more than dogmatic obedience. I agree that there are many sites which would be well served by following his recommendations - but if you want polish you cannot avoid breaking his commandments. That and the ridiculous deification.Floc
Also: because saying Jakob Nielsen says you shouldn't do that is a terrible argument.Floc
Not sure where the "answer" in context was here. You started with a comment about UX, which is erroneous (Jakob Nielsen is full of it here, not worth my time arguing about it though). And then ended up discussing Javascript, though markdown was the context.Thumbscrew
Removed unpopular opinion.Shanitashank
I'm going to add here that THIS is also preferable as a global solution. It keeps your Markdown clean, which is the point of Markdown.Weisberg
catch a bug, for plain javascript, shoule be: javascript.links -> document.links ?Uncrowned
F
95

With Markdown v2.5.2, you can use this:

[link](URL){:target="_blank"}
Felic answered 22/1, 2015 at 12:54 Comment(11)
I tried this and it didn't work for me. Using with django 1.6Scalade
Works with Jekyll v2.4.0 (might work with earlier versions as well)Quadri
This is kramdown (and as Jekyll uses kramdown, it works with Jekyll).Moises
Cannot seem to get this syntax to work in GitLab. I'm not sure which version of Markdown is currently in use.Outbuilding
Is there a way of making this the default so I don't have to specify it for every link?Coryphaeus
worked with jekyll 3.7.2. Also learned if you want to use with inline style you can use Markdown like this [Link](https://example.org/){:target="_blank"}{:style="color: pink; font-size:20px;"}Marasco
for those who are interested: this does not work neither for Jupyter Notebook nor for Python Dash (version 0.39.0)Shalne
Work with MkDocs 1.2.*, thanks for this answer, should be accepted as the best.Roth
I found that the underscore _ is optional. Using {:target="blank"} works the same. And in my buggy text editor, the underscore makes the rest of the file look italicKloman
Works for mkdocs but you have to enable the attr_list extension, see github.com/mkdocs/mkdocs/issues/1958Tussah
Works with @Nuxt/ContentDeodar
B
29

So, it isn't quite true that you cannot add link attributes to a Markdown URL. To add attributes, check with the underlying markdown parser being used and what their extensions are.

In particular, pandoc has an extension to enable link_attributes, which allow markup in the link. e.g.

[Hello, world!](http://example.com/){target="_blank"}
  • For those coming from R (e.g. using rmarkdown, bookdown, blogdown and so on), this is the syntax you want.
  • For those not using R, you may need to enable the extension in the call to pandoc with +link_attributes

Note: This is different than the kramdown parser's support, which is one the accepted answers above. In particular, note that kramdown differs from pandoc since it requires a colon -- : -- at the start of the curly brackets -- {}, e.g.

[link](http://example.com){:hreflang="de"}

In particular:

# Pandoc
{ attribute1="value1" attribute2="value2"}

# Kramdown
{: attribute1="value1" attribute2="value2"}
 ^
 ^ Colon
Baryta answered 24/5, 2018 at 1:50 Comment(3)
This worked for me in our custom markdown environment. Thanks!Gallego
What about for reference links?Criss
{target="_blank"} works if you try to specify it in Wiki.js. For those that are curious. This helped me get the functionality I wanted for specific links.Wedding
O
18

One global solution is to put <base target="_blank"> into your page's <head> element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in

Overlie answered 26/1, 2018 at 21:14 Comment(0)
Z
13

Not a direct answer, but may help some people ending up here.

If you are using GatsbyJS there is a plugin that automatically adds target="_blank" to external links in your markdown.

It's called gatsby-remark-external-links and is used like so:

yarn add gatsby-remark-external-links

plugins: [      
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [{
        resolve: "gatsby-remark-external-links",
        options: {
          target: "_blank",
          rel: "noopener noreferrer"
        }
      }]
    }
  },

It also takes care of the rel="noopener noreferrer".

Reference the docs if you need more options.

Zarf answered 23/6, 2020 at 5:51 Comment(0)
K
12

For ghost markdown use:

[Google](https://google.com" target="_blank)

Found it here: https://cmatskas.com/open-external-links-in-a-new-window-ghost/

Khaddar answered 10/8, 2016 at 1:24 Comment(1)
i like your solution. as i've tried it with different configurations it seems that it only works in inline linking. maybe there is a way for linking with reference links. something like: [open new window][1] \n [1]: (https://abc.xyz" target="_blank). maybe i mistake something, or this isn't ment to work that way?Magnanimity
H
11

I'm using Grav CMS and this works perfectly:

Body/Content:
Some text[1]

Body/Reference:
[1]: http://somelink.com/?target=_blank

Just make sure that the target attribute is passed first, if there are additional attributes in the link, copy/paste them to the end of the reference URL.

Also work as direct link:
[Go to this page](http://somelink.com/?target=_blank)

Hengel answered 30/4, 2017 at 18:57 Comment(2)
For reference, here is the relevant documentation chapter.Splenetic
Thanks. This still works if the url already has query parameters too, adding &target=_blank: [Go to this page](http://somelink.com/?param=42&target=_blank)Cephalonia
R
7

You can do this via native javascript code like so:

 
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");

JSFiddle Code

Recollected answered 10/6, 2014 at 21:17 Comment(0)
U
7

In my project I'm doing this and it works fine:

[Link](https://example.org/ "title" target="_blank")

Link

But not all parsers let you do that.

Umbilication answered 22/6, 2015 at 13:51 Comment(1)
Almost works, but even your example renders with url encoded into the title attr, rather than as new attrs (view source or edit the node as html): <a href="https://example.org/" rel="nofollow" title="title&quot; target=&quot;_blank">Link</a>Middleaged
P
7

There's no easy way to do it, and like @alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.

<script>
    var links = document.querySelectorAll( '.post-content a' );  
    for (var i = 0, length = links.length; i < length; i++) {  
        if (links[i].hostname != window.location.hostname) {
            links[i].target = '_blank';
        }
    }
</script>

The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.

As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/

Phyliciaphylis answered 27/8, 2015 at 14:10 Comment(0)
T
3

If someone is looking for a global rmarkdown (pandoc) solution.

Using Pandoc Lua Filter

You could write your own Pandoc Lua Filter which adds target="_blank" to all links:

  1. Write a Pandoc Lua Filter, name it for example links.lua
function Link(element)

    if 
        string.sub(element.target, 1, 1) ~= "#"
    then
        element.attributes.target = "_blank"
    end
    return element

end
  1. Then update your _output.yml
bookdown::gitbook:
  pandoc_args:
    - --lua-filter=links.lua

Inject <base target="_blank"> in Header

An alternative solution would be to inject <base target="_blank"> in the HTML head section using the includes option:

  1. Create a new HTML file, name it for example links.html
<base target="_blank">
  1. Then update your _output.yml
bookdown::gitbook:
  includes:
    in_header: links.html

Note: This solution may also open new tabs for hash (#) pointers/URLs. I have not tested this solution with such URLs.

Theressathereto answered 23/2, 2022 at 1:14 Comment(0)
S
1

In Laravel I solved it this way:

$post->text= Str::replace('<a ', '<a target="_blank"', $post->text);

Not works for a specific link. Edit all links in the Markdown text. (In my case it's fine)

Sibilate answered 11/5, 2022 at 21:3 Comment(0)
H
1

If you work with MkDocs, you might be interested in the Open in a new tab - plugin

This plugin adds JS to open outgoing links and PDFs in a new tab.

Install the plugin using pip from PyPI:

pip3 install mkdocs-open-in-new-tab

Just add the plugin:

plugins:
  - search
  - open-in-new-tab

More about the plugin.

Hainaut answered 11/4, 2023 at 20:9 Comment(0)
C
0

I ran into this problem when trying to implement markdown using PHP.

Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.

In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.

Custumal answered 6/1, 2014 at 23:28 Comment(0)
D
0

I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.

Building on @davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:

    <script type="text/javascript" charset="utf-8">
      // Creating custom :external selector
      $.expr[':'].external = function(obj){
          return !obj.href.match(/^mailto\:/)
                  && (obj.hostname != location.hostname);
      };

      $(function(){
        // Add 'external' CSS class to all external links
        $('a:external').addClass('external');

        // turn target into target=_blank for elements w external class
        $(".external").attr('target','_blank');

      })

    </script>
Deadpan answered 21/2, 2014 at 11:52 Comment(0)
P
0

Automated for external links only, using GNU sed & make

If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:

sed -i 's|href="http|target="_blank" href="http|g' index.html

This can be further automated by adding above sed command to a makefile. For details, see GNU make or see how I have done that on my website.

Pietra answered 10/6, 2014 at 13:24 Comment(0)
H
0

You can add any attributes using {[attr]="[prop]"}

For example [Google] (http://www.google.com){target="_blank"}

Hibiscus answered 14/10, 2014 at 9:28 Comment(0)
E
0

For completed alex answered (Dec 13 '10)

A more smart injection target could be done with this code :

/*
 * For all links in the current page...
 */
$(document.links).filter(function() {
    /*
     * ...keep them without `target` already setted...
     */
    return !this.target;
}).filter(function() {
    /*
     * ...and keep them are not on current domain...
     */
    return this.hostname !== window.location.hostname ||
        /*
         * ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
         */
        /\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
 * For all link kept, add the `target="_blank"` attribute. 
 */
}).attr('target', '_blank');

You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).

and for a without jQuery version, check code below:

var links = document.links;
for (var i = 0; i < links.length; i++) {
    if (!links[i].target) {
        if (
            links[i].hostname !== window.location.hostname || 
            /\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
        ) {
            links[i].target = '_blank';
        } 
    }
}
Essie answered 4/2, 2015 at 10:48 Comment(0)
B
0

If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.

If you want to do this in all generated <a> tags, depends on your Markdown compiler, maybe you need an extension of it.

I am doing this for my blog these days, which is generated by pelican, which use Python-Markdown. And I found an extension for Python-Markdown Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab seems not work in Python-Markdown 3.x.

Blaine answered 9/10, 2020 at 22:25 Comment(0)
S
0

For React + Markdown environment:

I created a reusable component:

export type TargetBlankLinkProps = {
  label?: string;
  href?: string;
};

export const TargetBlankLink = ({
  label = "",
  href = "",
}: TargetBlankLinkProps) => (
  <a href={href} target="__blank">
    {label}
  </a>
);

And I use it wherever I need a link that open in a new window.

Sacrum answered 11/6, 2022 at 7:10 Comment(0)
L
0

For "markdown-to-jsx" with MUI v5

This seem to work for me:

import Markdown from 'markdown-to-jsx';

...

  const MarkdownLink = ({ children, ...props }) => (
    <Link {...props}>{children}</Link>
  );

...

          <Markdown
            options={{
              forceBlock: true,
              overrides: {
                a: {
                  component: MarkdownLink,
                  props: {
                    target: '_blank',
                  },
                },
              },
            }}
          >
            {description}
          </Markdown>
Leverick answered 29/6, 2022 at 15:39 Comment(0)
P
-3

This works for me: [Page Link](your url here "(target|_blank)")

Prouty answered 23/10, 2018 at 16:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.