Simple self-contained HTML files from R

Hi,

I am working on a new R package that has some web resources in the inst/ folder. One of the HTML files, let's call it index.html, refers to various CSS and JS resources. Is there a straightforward way (from R) to have those resources "injected" into the HTML file either "as-is" or as base64 encoded (or something similar).

I thought that using rmarkdown::pandoc_convert() would work with the --self-contained flag, but pandoc is a little too ambitious for what I need and does not preserve styling. I JUST want the CSS and JS resources to be embedded into the HTML so that it is self-contained.

I tried base64 encoding the JS file, for example, using the base64enc package and then manually inserting this into the HTML file as a data URL but I couldn't get this to work, maybe I did something wrong.

Any help or guidance is much appreciated.

Here is some example files, if it helps!

# (index.html)
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Test</title>
    <script src="main.js"></script>
  </head>
  <body>
    <h1>Test</h1>
  </body>
</html>
# (main.js)
console.log("Can you hear me?")

I would be happy with:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Test</title>
    <script src="data:text/plain;base64,..."></script>
  </head>
  <body>
    <h1>Test</h1>
  </body>
</html>

or

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Test</title>
    <script>console.log("Can you hear me?")</script>
  </head>
  <body>
    <h1>Test</h1>
  </body>
</html>

So I ended up getting this to work with base64 encoding via the {base64enc} package. I just encoded it and then inserted it into the HTML document using {whisker}.

I am not sure what you are aiming at.
For generating HTML the package htmltools is being used. E.g. :

library(htmltools) 
#> Warning: package 'htmltools' was built under R version 4.1.1

# display function from https://github.com/rstudio/htmltools/issues/77 :
display_html_file <- function(x) {
  file <- tempfile()
  save_html(x, file)
  cat(readLines(file), sep = "\n")
  rm(file)
}

# generate contents of HTML document  (full HTML added by `save_html` )
x <- list(
  tags$head(tags$title('Test')),
  tags$head(tags$script(src = "myscript.js")),
  tags$body(h1('Test')
  )
)

display_html_file(x)
#> <!DOCTYPE html>
#> <html lang="en">
#> <head>
#> <meta charset="utf-8"/>
#> <style>body{background-color:white;}</style>
#> 
#>   <title>Test</title>
#>   <script src="myscript.js"></script>
#> </head>
#> <body>
#>   <h1>Test</h1>
#> </body>
#> </html>
Created on 2021-09-08 by the reprex package (v2.0.0)

The extra lines with DOCTYPE, meta and style are generated by the save_html function in display_html_file .

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.