9.2 Display HTML widgets

HTML widgets (https://htmlwidgets.org)\index{HTML!widgets} are typically interactive JavaScript applications, which only work in HTML output. If you knit an Rmd document containing HTML widgets to a non-HTML format such as PDF or Word, you may get an error message like this:

Error: Functions that produce HTML output found in document
targeting X output. Please change the output type of this
document to HTML. Alternatively, you can allow HTML output in
non-HTML formats by adding this option to the YAML front-matter
of your rmarkdown file:

  always_allow_html: yes

Note however that the HTML output will not be visible in
non-HTML formats.

There is actually a better solution than the one mentioned in the above error message, but it involves extra packages. You can install the webshot package (Chang 2019) in R and also install PhantomJS:


Then if you knit an Rmd document with HTML widgets to a non-HTML format, the HTML widgets will be displayed as static screenshots. The screenshots are automatically taken in knitr. Section 2.10 of the bookdown book contains more information on finer control over the screenshots.


Chang, Winston. 2019. Webshot: Take Screenshots of Web Pages. https://github.com/wch/webshot/.