mchen
mchen

Reputation: 10156

R Shiny incorrect parsing of user defined javascript?

From what I gather, if I want to include a bit of javascript in my Shiny App, I do something like:

shinyUI(
    fluidPage(
        tags$head(
            tags$script("if (1 > 0) {1}")
        )
    )
)

However, this causes an error in my browser, because if you do a 'view source' you see the actual javascript generated by Shiny is:

<script>if (1 &gt; 0) {1}</script>

It appears the > is incorrectly converted to &gt;. Now, is this because I'm not including javascript in Shiny in the right way, or is it a bug (or indeed a feature)? More importantly, is there any way round this?

Upvotes: 2

Views: 193

Answers (1)

jdharrison
jdharrison

Reputation: 30425

The tags function carries out HTML escaping. If you dont want escaping to be carried out you need to use HTML function:

require(shiny)
runApp(list(
  ui = bootstrapPage(
    numericInput('n', 'Number of obs', 100),
    plotOutput('plot'),
    tags$head(
      tags$script(HTML("if (1 > 0) {1}"))
    )
  ),
  server = function(input, output) {
    output$plot <- renderPlot({ hist(runif(input$n)) })
  }
))

There is now an includeScript function which wraps up the HTML function and the tags etc for you if your script is in a file. The key part is tags$script(HTML(paste(lines, collapse = "\r\n") which is basically what you are doing here.

Upvotes: 2

Related Questions