3

Struggling with R Markdown HTML _site.yml page. Within my navigation bar, I've got href's pointing to different website links and I can't figure our where to include the

target="_blank"

statement so links open in a new tab. Href links don't follow the normal html format in RMarkdowns _site.yml file.

    - text: "TWITTER"
      icon: fa-twitter
      href: https://twitter.com
    - text: "GITHUB"
      icon: fa-github
      href: https://github.com
    - text: "SLACK"
      icon: fa-slack
      href: https://slack.com

3 Answers3

3

Basically the best course of action is to create a js code that automatically adds target="_blank" to any external links. And taking into account the fact that internal links generated by rmarkdown are relative. We can easily create a regular expression that test for the existence of an external link then if found append target="_blank"

First create : links.js

(function() {
  for (const link of document.getElementsByTagName('a')) {
    if (/^(https?:)?\/\//.test(link.getAttribute('href'))) link.target = '_blank';
  }
})();

Add a script tag to include_footer.html

<script type="text/javascript" src="links.js"></script>

include include_footer in _site.yml

output:
  html_document:
    includes:
      after_body: include_footer.html
Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21
  • it looks like an elegant solution but I couldnt make it work. Where do you save links.js? Is it enought to save it to the footer? – RockScience Oct 14 '20 at 10:12
  • save `link.js` in the same folder with footer. Yeah It'll work if you put the content of the `js` file inside the footer – Abdessabour Mtk Oct 14 '20 at 10:46
  • @RockScience if you have a js folder then put it in it then change the `src` attrib of `script` tag – Abdessabour Mtk Oct 14 '20 at 11:16
  • Thank you! For the reference I had to move `links.js` to the *final* location of footer.html (ie: inside subfolder /_site). it now works like a charm – RockScience Oct 15 '20 at 11:44
2

You can create a redirect page for each one like this:

    - text: "TWITTER"
  icon: fa-twitter
  href: twitter_redirect.html

and then for twitter_redirect.html (etc), use window.open followed by window.history.back.

<!DOCTYPE html>

<html>
<head>
</head>
<body onload="myFunction()">

  <script>
    function myFunction() {
    window.open('https://twitter.com/', '_blank');
    window.history.back();
    }
  </script>
</body>
Eric
  • 166
  • 5
0

Refer the JScode from @Abdessabour Mtk,

---  
title: "BookMark"  
output: html_document  
---  

```{r setup, include=FALSE}  
knitr::opts_chunk$set(echo = TRUE)  
library(knitr)  
```  

[google](https://www.google.com)  
...

```{js, echo=FALSE}  
(function() {  
  for (const link of document.getElementsByTagName('a')) {  
    if (/^(https?:)?\/\//.test(link.getAttribute('href'))) link.target = '_blank';  
  }  
})();  
```  
quan
  • 68
  • 5