thothal
thothal

Reputation: 20399

Add javascript to your shiny module

Background

I want to include some javascript in my shiny module, but regardless of what I tried the java script does not appear in the final app. What am I doing wrong?

Code

library(shiny)

moduleUI <- function(id) {
   ns <- NS(id)
   js <- 'window.alert("fired from within the module");'
   tags$body(tags$script(HTML(js))) ## does not work
   tags$head(tags$script(HTML(js))) ## does not work either
   div("I am the only element")
}


module <- function(input, output, session) {
}

ui <- fluidPage(
   moduleUI("test"),
   tags$body(tags$script(HTML('window.alert("fired from the main");')))
)

server <- function(input, output, session) {
   handle <- callModule(module, "test")
}

shinyApp(ui = ui, server = server)

Upvotes: 2

Views: 2031

Answers (1)

A. Suliman
A. Suliman

Reputation: 13135

Try, as I think you define the script but you didn't attach it to any HTML element

moduleUI <- function(id) {
  ns <- NS(id)
  js <- 'window.alert("fired from within the module");'
  #tags$body(tags$script(HTML(js))) ## does not work
  #tags$head(tags$script(HTML(js))) ## does not work either
  div(tags$head(tags$script(HTML(js))) ,"I am the only element")
}

Upvotes: 4

Related Questions