Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render JavaScript code chunk console output

I would like to write some JavaScript in RMarkdown and print the results into the knitted document. Is there some simple way to render stuff into the document, e.g. with console.log() calls? I found out I can create new div elements and append them to the document's DOM, however, that would require a lot of boilerplate as a general solution.

E.g. say I have the following code chunk:

```{js}
function foo() {
   return "foo"
}

console.log(foo())
```

I would like some output chunk like this get rendered below:

> foo

Any ideas?

like image 492
Adam B. Avatar asked Dec 07 '25 16:12

Adam B.


1 Answers

It sounds like you are requesting the javascript be evaluated during the knitting process before the results get passed to pandoc for conversion.

Therefore you would need to register a custom knitting engine to evaluate the code and return the results. Here are two examples that uses the {chromote} package:

Option 1

Don't use console.log() and just return the output from the javascript.

---
title: "Custom JS Knitr"
output: html_document
date: "2024-04-25"
---

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

knitr::knit_engines$set(my_js = function(options) {
  code <- paste(options$code, collapse = "\n")
  b <- chromote::ChromoteSession$new()
  out <- b$Runtime$evaluate(code)$result$value
  knitr::engine_output(options, options$code, out)
})
```

```{my_js}
function foo() {
  return "foo"
};

foo();
```

Option 2

Use console.log() after registering a callback on messages added to the console and return the message text.

---
title: "Custom JS Knitr"
output: html_document
date: "2024-04-25"
---

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

knitr::knit_engines$set(my_js = function(options) {
  code <- paste(options$code, collapse = "\n")
  b <- chromote::ChromoteSession$new()
  console_log <- NULL
  b$Console$messageAdded(callback = \(x) console_log <<- c(console_log, x$message$text[[1]]))
  out <- b$Runtime$evaluate(code)$result$value
  knitr::engine_output(options, options$code, console_log)
})
```

```{my_js}
console.log("Hello world")
```
like image 61
the-mad-statter Avatar answered Dec 09 '25 07:12

the-mad-statter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!