2.11 Web pages and Shiny apps

Similar to HTML widgets, arbitrary web pages can be embedded in the book. You can use the function knitr::include_url() to include a web page through its URL. When the output format is HTML, an iframe is used;8 in other cases, knitr tries to take a screenshot of the web page (or use the custom screenshot you provided). All chunk options are the same as those for HTML widgets. One option that may require your special attention is the delay option: HTML widgets are rendered locally, so usually they are fast to load for PhantomJS to take screenshots, but an arbitrary URL may take longer to load, so you may want to use a larger delay value, e.g., use the chunk option screenshot.opts = list(delay = 5).

A related function is knitr::include_app(), which is very similar to include_url(), and it was designed for embedding Shiny apps via their URLs in the output. Its only difference with include_url() is that it automatically adds a query parameter ?showcase=0 to the URL, if no other query parameters are present in the URL, to disable the Shiny showcase mode, which is unlikely to be useful for screenshots or iframes. If you do want the showcase mode, use include_url() instead of include_app(). Below is a Shiny app example (Figure 2.6):

knitr::include_app("https://yihui.shinyapps.io/miniUI/",
  height = "600px")

FIGURE 2.6: A Shiny app created via the miniUI package; you can see a live version at https://yihui.shinyapps.io/miniUI/.

Again, you will see a live app if you are reading an HTML version of this book, and a static screenshot if you are reading other types of formats. The above Shiny app was created using the miniUI package (R-miniUI?), which provides layout functions that are particularly nice for Shiny apps on small screens. If you use normal Shiny layout functions, you are likely to see vertical and/or horizontal scrollbars in the iframes because the page size is too big to fit in an iframe. When the default width of the iframe is too small, you may use the chunk option out.width to change it. For the height of the iframe, use the height argument of include_url()/include_app().

Shiny apps may take even longer to load than usual URLs. You may want to use a conservative value for the delay option, e.g., 10. Needless to say, include_url() and include_app() require a working Internet connection, unless you have previously cached the chunk (but web pages inside iframes still will not work without an Internet connection).


  1. An iframe is basically a box on one web page to embed another web page.↩︎