htmlrbookdown

Make all hyperlinks in R Bookdown Code Chunks open in new tab


I'm wondering how I can add the target="_blank" attribute to hyperlinks within code chunks in a knitted HTML file (created from bs4_book in Bookdown).

That is, change all hyperlinks in the following example HTML:

<pre class="downlit sourceCode r">
     <code class="sourceCode R">
          <span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span>
          <span class="op">(</span>
          <span class="va"><a href="https://github.com/duncanplee/CARBayes">CARBayes</a></span>
          <span class="op">)</span>
     </code>
</pre>

These code chunks are created in R Markdown using:

Here is some raw markdown where I present my code chunk:

```{r echo=FALSE}
library(CARBayes)
```

And here I discuss the above code chunk

Perhaps there is some fancy JS that could work?


Solution

  • I have written some JavaScript to perform this task, which you can include into your book via the includes option of your output format. For example, you create a file after_body.html:

    <script src="https://cdn.jsdelivr.net/npm/@xiee/utils/js/external-link.min.js" defer></script>
    

    Then configure your output format:

    output:
      bookdown::bs4_book:
        includes:
          after_body: "after_body.html"
    

    You may read this post if you are interested in more technical details.