It seems like you are interested in having the javascript code evaluated before passing the results to pandoc for conversion while knitting.
To achieve this, you will need to create a custom knitting engine that can evaluate the code and return the results. Below are two examples using the {chromote}
package:
Option 1
Avoid using console.log()
and simply 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
Utilize console.log()
after setting up a callback on console messages, then 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")
`