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?
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:
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();
```
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")
```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With