简体   繁体   中英

Why is console.log not a function in Shiny for R?

I include JavaScript in Shinys ui.R like this:

tags$body(tags$script(src="someJs.js"))

Within my someJs.js I have a function

function someFunc1() {
    ....;
}

... some more code ...

console.log(variable1);

The console.log is outside of the function soemFunc1() . When I start the App and have a look at the console, I get

console.log() is not a function.

Why is that?

I also load d3 in the head tags$head(tags$script(src="d3.v3.min.js")) . When I try d3.select... in the console, I also get

d3 is not a function.

However, I use d3 in my app for styling.

What is Shiny doing with the js . Is there an object where it attaches everything to?!

Here a an example, easy to reproduce.

ui.R

library(shiny)

shinyUI(fluidPage(
    tags$head(tags$script(src="https://d3js.org/d3.v3.min.js")),
    tags$head(tags$script(src="test.js")),
            mainPanel(
                    tags$div(id = "test", "test test test")
            )
    )

)

server.R

library(shiny)

shinyServer(function(input, output) {

})

create a www folder in the same directory where server.R and ui.R are and save a js file with the name test.js with the following content:

console.log("This will cause error")

Now, go ahead and open the console. It says

console.log() is not a function

Try type into the console of the browser d3 . It says

d3 is not a function.

console.log() is a JavaScript function, so you cannot call it in R-Shiny and expect it to run in JavaScript. You have to explicitly tell Shiny to make that call in JavaScript.

Since it is a fairly common operation for me, I included it in the package shinyjs , you can call the logjs() function in R and it will write output to the javascript console.

Example:

shinyApp(
    ui = fluidPage(
        shinyjs::useShinyjs() # Set up shinyjs
    ),
    server = function(input, output) {
        shinyjs::logjs("hello")
    }
)

I'm not sure I fully understand what you are trying to do, but if you are trying to use console.log() in the JavaScript to see something in the JavaScript console then you shouldn't have a problem:

library(shiny)
ui <- shinyUI(fluidPage(
  mainPanel(
      tags$script(HTML(
        "console.log('Here is some text');"
        ))
  )
)
)

server <- shinyServer(function(input, output, session) {

})
# Run the application
shinyApp(ui = ui, server = server)

If you run this, and then inspect the page using Chrome or RStudio's web-browser, and click on console, which gives you the JavaScript console, you will see the output from the console.log() function.

If you want to print to the R console you have to use print or cat from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM